Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling attribute accessor methods from within the class

Tags:

ruby

I am trying to get call one of my classes attribute writers, but for some reason it never gets called. Here's some code that'll make this clearer:

class Test
  attr_reader :test

  def test=(val)
    puts 'Called'
    @test = val
  end

  def set_it(val)
    test = val
  end
end

obj = Test.new
obj.set_it 5
puts obj.test
=> nil

The puts statement at the end outputs 'nil'. Adding a debugging statement to test= shows it is never called. What am I doing wrong?

Update

I re-wrote this question partially, as I didn't truly understand the problem when I wrote it. So the question is much more generalized now.

like image 653
Mark A. Nicolosi Avatar asked Feb 28 '23 23:02

Mark A. Nicolosi


1 Answers

You're doing nothing "wrong" per se. Ruby just thinks you intend to set the local variable test to val, not call the test= method. self.test = val will do what you expect.

like image 171
Logan Capaldo Avatar answered Mar 05 '23 18:03

Logan Capaldo