Ben
Ben

Reputation: 127

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.

Upvotes: 0

Views: 244

Answers (2)

mu is too short
mu is too short

Reputation: 434665

You call attr_accessor on mock_person's singleton class using class_eval:

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

Upvotes: 0

Sagar Pandya
Sagar Pandya

Reputation: 9497

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"

Upvotes: 1

Related Questions