从动态添加的方法更改实例属性

发布于 2023-02-26 00:30:55 字数 595 浏览 21 评论 0原文

我尝试更改运行时添加的方法的实例属性,并在接下来的流程方法中继续使用相同的属性。

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花坊 2023-03-05 00:30:55

因为在您的 class_eval 示例行中用双引号括起来,因此 Ruby 准备替换 @s 变量(在这个阶段这个变量等于 nil ). 如此更改您的代码:

Test.class_eval('def test_2; puts "test_2 1 #{@s}";   @s = 7; test_1; puts "test_2 2 #{@s}"; end')
# =>
    start 5
    test_2 1 5
    test_1 4
    test_2 2 4
    flow 4

或将块与 class_eval 一起使用(我相信这要好得多)

Test.class_eval do
  def test_2
    puts "test_2 1 #{@s}"
    test_1
    puts "test_2 2 #{@s}"
  end
end

还有一个注意事项。 您的 @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 equals nil). Change your code so:

Test.class_eval('def test_2; puts "test_2 1 #{@s}";   @s = 7; test_1; puts "test_2 2 #{@s}"; end')
# =>
    start 5
    test_2 1 5
    test_1 4
    test_2 2 4
    flow 4

or use block together with class_eval (that's much better, I believe)

Test.class_eval do
  def test_2
    puts "test_2 1 #{@s}"
    test_1
    puts "test_2 2 #{@s}"
  end
end

And one more note. Your @s = 7 assignment is redundant because in test_1 method you immediately prepare yet another assignment @s = 4.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击“接受”或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文