我对Ruby很新,我正在尝试编写一个方法来动态地将方法添加到现有的ruby类中,这是我到目前为止所拥有的:
class Person
end
def attr_addr (target, attr)
target.send :attr_accessor, attr
end
bob = Person.new
attr_addr(Person,"name")
bob.name = "bob"
但我明白了:
private method `name=' for ....
我在这里做错了什么? - 我完全使用了错误的方法吗? - )?
答案 0 :(得分:3)
您的原始代码适合我。无论如何,这是另一种写作方式:
def attr_addr(target, attr)
target.instance_eval "attr_accessor :#{attr}"
end
这是在IRB会议中采取的行动:
>> bob = Person.new
=> #<Person:0x00000000df8798>
>> bob.name = "bob"
NoMethodError: undefined method `name=' for #<Person:0x00000000df8798>
from (irb):6
from /home/michi/.rbenv/versions/1.9.3-p0/bin/irb:12:in `<main>'
>> attr_addr(Person, "name")
=> nil
>> bob.name = "bob"
=> "bob"
>> bob
=> #<Person:0x00000000df8798 @name="bob">
答案 1 :(得分:0)
它对我有用(Ruby 1.8.7):
irb(main):001:0> class Person; end
=> nil
irb(main):003:0> Person.send :attr_accessor, :name
=> nil
irb(main):004:0> p = Person.new
=> #<Person:0x7f9716bad768>
irb(main):005:0> p.name = "test"
=> "test"
irb(main):006:0> p.name
=> "test"