Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
谁能告诉我,为什么这不起作用:
class A attr_accessor :b end a = A.new a.instance_eval do b = 2 end a.b => nil
我在做什么错?
罪魁祸首在于这部分代码:
a.instance_eval do b = 2 end
尽管b = 2在您的实例的上下文中进行评估,但它不会调用 setter。相反,它只是创建一个b在当前范围内调用的新局部变量。要调用 setter,您必须进一步澄清您的代码以解决歧义:
b = 2
b
a.instance_eval do self.b = 2 end
改变: