我在用class_eval
编写要在当前类的上下文中执行的代码。在下面的代码中,我想添加一个用于属性值更改的计数器。
class Class
def attr_count(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name # create the attribute's getter
class_eval %Q{
@count = 0
def #{attr_name}= (attr_name)
@attr_name = attr_name
@count += 1
end
def #{attr_name}
@attr_name
end
}
end
end
class Foo
attr_count :bar
end
f = Foo.new
f.bar = 1
我的理解class_eval
是它评估块在运行时类的上下文中- 就我而言,在class Foo
。我期望上面的代码运行类似于:
class Foo
attr_count :bar
@count = 0
def bar= (attr_name)
@attr_name = attr_name
@count += 1
end
def bar
@attr_name
end
end
然而上面的代码导致了错误,错误是由@count += 1
。我不明白为什么@count
has nil:NilClass
作为其超级?
(eval):5:in `bar=': undefined method `+' for nil:NilClass (NoMethodError)
另一方面,@selman 给出了一个解决方案@count
在实例方法中进行赋值并且它有效。
class Class
def attr_count(attr_name)
#...
class_eval %Q{
def #{attr_name}= (attr_name)
@attr_name = attr_name
if @count
@count += 1
else
@count = 1
end
end
#...
}
end
end
为什么改变变量作用域有效?如何class_eval
执行它的下面的字符串?