Ben Ben - 4 months ago 7
Ruby Question

Setting an attr_accessor instance variable in 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


Is there a cleaner way to do this? Ideally when I use
instance_variable_set
, I want to specify that the variable should be
attr_accessor
.

Answer

Not entirely sure what you're trying to do but have a look at the Struct class. For your example you may be looking for something like this:

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