Calling attribute access methods from a class

I am trying to get a call to one of my class attribute attributes, but for some reason it is never called. Here is the code that will 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 job at the end prints "nil". Adding a debug statement to test = indicates that it is never called. What am I doing wrong?

Update

I re-wrote this question in part, since I really did not understand the problem when I wrote. Therefore, the question is much more generalized.

+4
ruby
Feb 23 '09 at 3:16
source share
2 answers

You are not doing anything "wrong." Ruby just thinks that you intend to set the local test variable to val and not call the test= method. self.test = val will do what you expect.

+8
Feb 23 '09 at 3:22
source share

Here are some other resources on this (apparently common) problem:

Another question: Why do I need ruby ​​setters? classroom qualifications?

From this guys blog :

As a newbie to Ruby, you probably once did race = "hooman" but you noticed that it didn’t work and you said to yourself, "I won’t let this happen to me again. From now on, Ill prepend self. Every time when I call the method! "

0
Mar 14 '09 at 1:56
source share



All Articles