在Ruby中设置attr_accessor实例变量

时间:2016-07-26 23:14:30

标签: ruby

mock_person = Object.new
mock_person.instance_variable_set(:@first_name, 'John')
mock_person.first_name # NoMethodError: Undefined method `first-name`


mock_person = Object.new
def mock_person.first_name()
    return 'John'
end
mock_person.first_name # This works

有更清洁的方法吗?理想情况下,当我使用instance_variable_set时,我想指定变量应为attr_accessor

2 个答案:

答案 0 :(得分:1)

不完全确定你要做什么,但要看看Struct课程。对于你的例子,你可能正在寻找这样的东西:

Struct.new("Person", :first_name)
mock_person = Struct::Person.new('John')
mock_person.first_name #=> "John"

答案 1 :(得分:0)

您使用singleton classattr_accessor的{​​{3}}上致电mock_person

mock_person = Object.new
mock_person.singleton_class.class_eval { attr_accessor :first_name }
mock_person.first_name = 'pancakes'
puts mock_person.first_name
# => pancakes
puts mock_person.instance_variable_get(:@first_name)
# => pancakes