Fred Willmore Fred Willmore - 1 month ago 8
Ruby Question

attr_accessor not updating value

I have a class with attribute accessors:

class MyClass
attr_accessor :a, :b

def initialize
@a = 1
@b = 2
end

def update_values options
a = options[:a]
b = options[:b]
end
end


I think that after calling update_values, a and b should retain their new values:

describe MyClass do
before do
@thing = MyClass.new
end

it 'should set a and b' do
expect(@thing.a).to eq 1
expect(@thing.b).to eq 2
@thing.update_values a: 2, b: 5
expect(@thing.a).to eq 2
expect(@thing.b).to eq 5
end
end


This is not happening - the test fails:

Failures:

1) MyClass should set a and b
Failure/Error: expect(@thing.a).to eq 2

expected: 2
got: 1

(compared using ==)


Isn't this how attribute accessors should work? What am I missing?

Answer

You are just defining local variables a and b.

What you want instead, is to set new values for instance variables a and b. Here is how you can do that:

def update_values options
  self.a = options[:a] # or @a = options[:a]
  self.b = options[:b] # or @b = options[:b]
end

Now:

foo = MyClass.new
#=> #<MyClass:0x007f83eac30300 @a=1, @b=2>
foo.update_values(a: 2, b: 3)
foo #=>#<MyClass:0x007f83eac30300 @a=2, @b=3>
Comments