从动态添加的方法更改实例属性
我尝试更改运行时添加的方法的实例属性,并在接下来的流程方法中继续使用相同的属性。
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 test_2 1 test_1 4 test_2 2 流程 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
). 如此更改您的代码:或将块与
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
.