我正在使用class_eval
编写要在当前类的上下文中执行的代码。在下面的代码中,我想添加一个计数器来更改属性值。`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
有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
如何执行其以下字符串?
你是如何喜欢CS169课程的? :) – 2012-10-17 01:36:52