Variables and Assignment


To store a number or a string in your computer's memory for use later in your program, you need to give the number or string a name. Programmers often refer to this process as assignment and they call the names variables. A variable springs into existence as soon as the interpreter sees an assignment to that variable.

A bareword is any combination of letters, numbers, and underscores, and is not qualified by any symbols (Reference: http://alumnus.caltech.edu/~svhwan/prodScript/avoidBarewords.html). Local variables and barewords look similar; they must start with either the underscore character (_) or a lowercase letter, and they must consist entirely of letters, numbers, and underscores. Remember, local variable references look just like method invocation expressions and Keywords can't be used as variable names.

Method calls can also be barewords, such as my_method. gets is a method call; so is system. Whenever Ruby sees a bareword, it interprets it as one of three things: (a) If there's an equal sign (=) to the right of the bareword, it's a local variable undergoing an assignment. (b) Ruby has an internal list of keywords and a bareword could be a keyword.(c) If the bareword is not (a) or (b) above, the bareword is assumed to be a method call. If no method by that name exists, Ruby raises a NameError.

The p004stringusage.rb shows us some more usage with strings.

In the example:
x = "200.0".to_f
the dot means that the message "to_f" is being sent to the string "200.0", or that the method to_f is being called on the string "200.0". The string "200.0" is called the receiver of the message. Thus, when you see a dot in this context, you should interpret it as a message (on the right) being sent to an object (on the left).

Summary

I have listed down all the important points you need to remember after you have completed the following topics: Introduction, Installation, First Ruby program, Features of Ruby, Numbers in Ruby, String fundamentals and Variables and Assignment.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.com and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.