Using attr_accessor from inside class?

1.5k views Asked by At

I'm trying to use an attr_accessor from inside the class where it is defined, to no avail. Why does this not work?

I would expect the following to output "new" in IRB:

irb(main):016:0> foo = StringClass.new
=> #<StringClass:0x2fbf2c0 @thing="old">
irb(main):017:0> foo.output
old
=> nil
irb(main):018:0> foo.change
=> "new"
irb(main):021:0> foo.output
old
=> nil

Here's the implementation:

class StringClass
  def initialize
    @thing = "old"
  end

  attr_accessor :thing

  def output
    puts thing
  end

  def change
    thing = "new"
  end
end

I can see that the thing= method is defined. I don't understand why that method is not being called when I try changing the value.

2

There are 2 answers

2
maicher On BEST ANSWER

That is, because those methods should be called with self:

class StringClass
  def initialize
    @thing = "old"
  end

  attr_accessor :thing

  def output
    puts self.thing
  end

  def change
    self.thing = "new"
  end
end
0
Amit Suroliya On

Try this -

class StringClass
   ......

   def change
     self.thing = "new"
   end
 end
  1. foo = StringClass.new
  2. foo.change => "new"