Ben Ben - 1 year ago 81
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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download