通过动态添加的方法更改实例属性
我尝试从运行时添加的方法更改实例属性,并在下一个流程方法中继续使用相同的属性。
class Test
def start
@s = 5
puts "start #{@s}"
end
def test_1
@s = 4
puts "test_1 #{@s}"
end
def flow
start
test_2
puts "flow #{@s}"
end
end
Test.class_eval("def test_2\n puts 'test_2 1 #{@s}'\n @s = 7\n test_1\n puts 'test_2 2 #{@s}'\n end\n")
t = Test.new
t.flow
结果是: 开始 5 测试_2 1 测试_1 4 测试_2 2 flow 4
所以我无法弄清楚跳过 test_2 1 打印的原因是什么以及为什么类属性的值没有从新的评估方法中更新。
I am try to change the instance attributes from the method added in run time and continue to use the same in next in flow methods.
class Test
def start
@s = 5
puts "start #{@s}"
end
def test_1
@s = 4
puts "test_1 #{@s}"
end
def flow
start
test_2
puts "flow #{@s}"
end
end
Test.class_eval("def test_2\n puts 'test_2 1 #{@s}'\n @s = 7\n test_1\n puts 'test_2 2 #{@s}'\n end\n")
t = Test.new
t.flow
The results of that is :
start 5
test_2 1
test_1 4
test_2 2
flow 4
So i coudl not figure out what is the reason of skipping the print of test_2 1 printing and why the value of the class attribute is not updated from the new evaluated method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为在您的示例行中,
class_eval
括在双引号中,因此 Ruby 准备替换@s
变量(在此阶段,此变量等于nil
)。更改您的代码:或者将 block 与
class_eval
一起使用(我相信这要好得多)还有一个注释。您的
@s = 7
分配是多余的,因为在test_1
方法中,您立即准备另一个分配@s = 4
。Because in your example line for
class_eval
enclosed in double quotes, therefore Ruby prepare a substitution for@s
variable (at this stage this variable equalsnil
). Change your code so:or use block together with
class_eval
(that's much better, I believe)And one more note. Your
@s = 7
assignment is redundant because intest_1
method you immediately prepare yet another assignment@s = 4
.