BinaryWebPark

How Ruby Decides What Is a Variable and What Is Not

October 11, 2012

When the ruby interpreter goes through your code and sees a word sitting in it all by its lonesome, it assumes the word is one of 3 things: a keyword, a method call, or a local variable.

What is a keyword and how does ruby recognize it?

A keyword is one of those words that is “special” in Ruby. It’s a reserved word that you can’t use as a variable name. For instance, “while” is a keyword and can’t be used as a variable name. Ruby recognizes these through its own internal listing. Here’s a handy list of keywords for Ruby 1.9 I found through Google: http://ruby-doc.org/docs/keywords/1.9/

The word could also be a local variable

A local variable is a variable that starts with a lower case letter or underscore and has limited scope. Limited scope means it is only visible to a small part of your Ruby program. For instance, a local variable inside a method definition is only visible within that method. You can’t access the variable outside the method.

Finally, the word could also be a method call

You’ve probably seen method calls before in some of my other blog posts (e.g., like the initialize method for the Car class I wrote for this example). Method calls have the “def” keyword in front of them and end with the “end” keyword.

So how does Ruby make its decision about the words in your code?

First, it checks its internal keyword list to see if the word is a keyword. If it’s not a keyword, and there’s an equal sign to teh right of the word, then it’s a local variable that is being assigned a value. If it’s not a keyword or local variable, then it’s assumed to be a method call.

If Ruby encounters something that doesn’t meet the criteria above, it returns an error message. For instance, suppose I just type “abc” in my Ruby code without assigning it any value or defining it as a method. Since it’s not a keyword, when you try to run the program, you’ll get an error similar to the following:

in `': undefined local variable or method `abc' for main:Object (NameError)