method's local variable with same name as another method

ruby

Solution

I think that the local variable is declared as soon as it's enunciated. In ruby the lookup is first to look for a local variable, if it exists it's used, and if not it looks for a method. This would mean that val = val declares the first val as local and the left-hand val then matches it (not sure about it I should check the ruby under microscope to be sure)

If you try

class A
  def val
    10
  end

  def test
    back = []
    x = val
    back << x
    val = x + 1
    back << val
    x = val
    back << x
  end
end

p A.new.test

then all is good, it prints [10, 11, 11] which means the first x = val calls the method, the second calls the local variable, presumably.

Problem

I was trying to figure out how Ruby handles local variables that have the same names as the methods in `self` class, and found a behavior that I do not understand: ``` class A def val 10 end def test val = val end end p A.new.test ``` this code prints `nil`. why?!

Original source

Related problems