This post originated from an RSS feed registered with Ruby Buzz
by Florian Frank.
Original Post: It's easy to confuse methods and local variables in Ruby
Feed Title: The Rubylution
Feed URL: http://rubylution.ping.de/xml/rss/feed.xml
Feed Description: The Rubylution is a weblog (mainly) about Ruby Programming.
I just tripped over this wire again. It's a bit embarrassing because I used to know it, but I forgot it again.
In Ruby methods and local variables can look exactly the same. So it's possible to define a method and assign values the a local variable of the same name:
You can see, that the execution of the assignment isn't what makes foo into a local variable. It's only important, that Ruby's parser encounters an assignment during its pass, not that it is actually executed.
If no value was assigned to the local variable, it will be nil. The same thing happened in the first example, the assignment was equivalent to foo = foo without any definition of the foo method before it.