Ben Ben - 8 months ago 20
Ruby Question

Setting an attr_accessor instance variable in Ruby

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

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

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


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:"Person", :first_name)
mock_person ='John')
mock_person.first_name #=> "John"