The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
It's easy to confuse methods and local variables in Ruby

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Florian Frank

Posts: 48
Nickname: ffrank
Registered: Dec, 2005

Florian Frank is a humanoid life-form, living on the third planet of the solar system.
It's easy to confuse methods and local variables in Ruby Posted: Mar 6, 2007 3:34 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Florian Frank
Latest Posts From The Rubylution

Advertisement

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:

def foo
  :foo
end

defined?(foo) # => "method"
foo = foo
defined?(foo) # => "local-variable"
foo # => nil

After the assignment the symbol foo now refers to the local variable foo. But it's nil and not :foo. Why?

Now look at this:

def foo
  :foo
end

defined?(foo) # => "method"
if false
  foo = foo
end
defined?(foo) # => "local-variable"
foo # => nil

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.

I hope, that I don't forget that again! ;)

Read: It's easy to confuse methods and local variables in Ruby

Topic: Installing Netbeans with Ruby/Rails support Previous Topic   Next Topic Topic: Setup a production ready ruby on rails application over apache and mongrel

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use