Fred Willmore Fred Willmore - 1 year ago 73
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

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

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

describe MyClass do
before do
@thing =

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

This is not happening - the test fails:


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 Source

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]


foo =
#=> #<MyClass:0x007f83eac30300 @a=1, @b=2>
foo.update_values(a: 2, b: 3)
foo #=>#<MyClass:0x007f83eac30300 @a=2, @b=3>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download