language-ruby icon indicating copy to clipboard operation
language-ruby copied to clipboard

Local variables?

Open asantos3 opened this issue 10 years ago • 4 comments

Why every type of variables except local ones supported, is this intended or ...?

asantos3 avatar Dec 05 '14 22:12 asantos3

Ruby's grammar is ambiguous when it comes to the left-hand side of assignment expressions. In this very limited case, this is a local variable:

def foo
  bar = 5
end

But if we expand it to this:

class Foo
  def bar=(value)
    @bar = value
  end

  def foo
    bar = 5
  end
end

Then bar is a method, not a local variable. Without having a full parse tree, it is impossible in Ruby to know if an assignment statement is an assignment to a local variable or a function call. (And even with the full parse tree, it can still be ambiguous since methods can be generated at runtime.)

lee-dohm avatar Dec 06 '14 01:12 lee-dohm

Actually, in both cases, bar is a local variable.

image

image

Ruby always treats assignment as assignment rather than a method call (this is where self.bar = comes into play, as this ensures we're calling the method.)

AgentAntelope avatar Dec 06 '14 21:12 AgentAntelope

Thanks for the correction. My example was bad.

lee-dohm avatar Dec 07 '14 00:12 lee-dohm

Well I hope you aren't just calling and breathing into the mic instead of sending a message :heart_eyes_cat: :wink:

envygeeks avatar Dec 16 '14 13:12 envygeeks