请考虑以下代码:
class Student
attr_accessor :age, :gender, :school
def explicit_school_setter
@school = "Some School"
end
end
bob = Student.new
bob.age = 16
bob.gender = :male
bob.instance_eval { school = :bvb } # ? Why is this not invoking the setter?
bob.age # => 16
bob.gender # => :male
bob.school # => nil
bob.instance_eval { explicit_school_setter }
bob.school # => "Some School"
bob.school = "Another School"
bob.school # => "Another School"
为什么setter无法在instance_eval
块中运行?
答案 0 :(得分:3)
当您致电school = :bvb
时,您正在创建一个本地变量。将其更改为self.school = :bvb
,您就完成了。
答案 1 :(得分:1)
D @school而不是下面的学校,如下所示
bob.instance_eval { @school = :bvb }