megas
megas

Reputation: 21791

Ruby scope variable

Here's the code:

class Something
   attr_accessor :x
   def initialize(x)
      @x = x
   end
   def get_x
      x
   end
end

something = Something.new(5)
something.get_x # => 5

Why interpreter returns 5 if x is just a local variable in get_x method? Thanks

Upvotes: 1

Views: 672

Answers (3)

fl00r
fl00r

Reputation: 83680

attr_accessor :x adds two methods for you:

def x=(val)
  @x = val
end

def x
  @x
end

So you don't actually need get_x getter if you've added attr_accessor method.

UPD

So the question is

class Something
  attr_accessor :x
  def initialize(x)
    @x = x
  end
  def set_x=(new)
    x = new
  end
end

Why won't x = new call default x setter: because default x setter is an instance method so you can call it for an object (Something instance) but not in your class like you try.

Upvotes: 4

Michael Kohl
Michael Kohl

Reputation: 66867

The attr_accessor defines a method x (and the setter x=) which gets called in get_x.

>> something.methods.grep /^x/
=> [:x, :x=]

Upvotes: 2

muffinista
muffinista

Reputation: 6736

x is also a method. attr_accessor :x adds x= and x to your class. So, get_x is calling the x method, and returning the value for @x. see http://www.rubyist.net/~slagell/ruby/accessors.html for details.

Upvotes: 5

Related Questions