为了更好地理解Ruby,我决定重新创建attr_accessor方法。成功地。我现在明白它是如何工作的,除了关于Ruby的语法糖的一个细节。下面是我创建attr_accessor中方法:Ruby的attr_accessor魔法定义方法
def attr_accessor(*attributes)
attributes.each do |a|
# Create a setter method (obj.name=)
setter = Proc.new do |val|
instance_variable_set("@#{a}", val)
end
# Create a getter method (obj.name)
getter = Proc.new do
instance_variable_get("@#{a}")
end
self.class.send(:define_method, "#{a}=", setter)
self.class.send(:define_method, "#{a}", getter)
end
end
我看到它的方式,我只定义了两个方法,obj.name
作为getter和obj.name=
作为二传手。但是当我在IRB中执行代码并调用obj.name = "A string"
时,它仍然有效,即使我没有空间定义该方法!
我知道这只是定义Ruby的魔法的一部分,但是究竟是什么使得这个工作成为可能?
呃哦,那个我的阅读理解,我好像回答了错误的问题:],对于你的+1。 – 2013-02-14 14:49:25