Variables in Ruby
Everything in Ruby is essentially an object, a thing that can be manipulated. These objects are manipulated by methods, sets of expressions that return a value.
Everything in Ruby is either an object or a method.
This is a good way to begin thinking about how to construct programs in Ruby. It is also the source of much confusion for Ruby beginners. When learning your first or second programming language it's not enough to simply memorize the hard and fast constructs of that language. While it's technically true that not everything in Ruby is an object, it helps programmers (especially beginners) to think in those terms. We will discuss objects in-depth in another chapter. For now, we will focus on variables.
When learning a computer language, it's sometimes beneficial to use a heuristic approach. Don't let technicalities confuse you in the early stages of learning. You'll never progress forward if you cannot grasp a firm high level understanding of the language. Keep this in mind as we discuss variables in Ruby.
What are variables?
Variables are NOT objects but they can be treated like objects. This is because once a variable is assigned it acts just like an object. Variables are used to reference objects. They are pointers to objects. Similar to how you would use variables in Algebra, the variable 'a' can be assigned to the integer 4 using the assignment operator:
4 4a =
After I open an IRB session I assign the value of 4 to the variable 'a'. I can now work with the variable 'a' as if it were an object. Here are a few examples:
5 9 a > 8 false a * 5 - 1 19a +
The first thing I did was add 5 to the variable 'a', which had a value of 4. The result of this is what we would expect, 4 + 5 = 9. However, it is important to understand that the variable 'a' remains unchanged afterward. It was stored in memory upon assigning it's value. So, by adding 'a' and 5 we performed an action and Ruby returned the result of that action. The next action is to check if 'a' is greater than 8 (written a > 8). As you can see, the interpreter returns the value "false". As we know, 'a' is 4 and 4 is certainly less than 8. Finally, we multiply 'a' by 5 and subtract 1. The result is what we should expect 4 * 5 = 20 and 20 - 1 = 19. This is interesting because there is a precedence of operations. How does the interpreter know to multiply before subtracting? The Ruby language is intuitive. The interpreter is aware of operator precedence. It will first check for parenthesis and exponents, followed by multiplication and division, followed by addition and subtraction.
It's important to realize that the assignment operator is not synonymous with 'equals'. The expression "a = 4" should be read as, "the variable 'a' is assigned a value of 4". It is tempting to look at the expression and think, "a equals 4". However, this is incorrect and a very common mistake made by beginners. In programming the sign for equals is "==", called "double equals". A single equals sign indicates 'assignment'. A double equals sign indicates 'equality'. Inexperienced programmers make the mistake of checking variables for equality with the assignment operator, leading to bugs and broken programs.
The rules of naming variables in Ruby are quite relaxed. The best practice is to use descriptive, meaningful words in lowercase separated by underscores. Other languages use conventions such as camelCase, PascalCase, or words-with-dashes. In Ruby, the convention is to create variables using "snake_case", that is to say, all lowercase words separated by underscores.
Ruby is a readable language. It's good design to write code that can be read and understood by other developers. One aspect of good design is having descriptive variable names. It's better to have a variable named, 'articles_written' as opposed to, 'aw'. Although it's a shorter name and therefore less typing, 'aw' doesn't have any significant meaning that's immediately recognizable. Other developers looking at this program will need to read more before understanding what that variable represents. However, a variable named, 'articles_written' makes it immediately recognizable as to what it represents.
Don't use Keywords
Every language has a number of built-in keywords, which are reserved words with meaning. These keywords are predefined by the language. They cannot be changed, nor used as variables. If you attempt to use, or rather misuse, a keyword, you will receive a syntax error. Here is a list of keywords in Ruby, taken from the official Ruby documentation:
alias and BEGIN begin break case class def defined do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield
A variable's scope is defined as where in the application a variable is accessible. There are four types of variable scope in Ruby, global, class, instance, and local. Each variable type can be inferred by the character that it begins with. We will explore this further in the chapter on classes. In addition, Ruby has two pseudo-variables that cannot be assigned a value, nil and self. Nil is the equivalent of null in other languages, it indicates no value. Self is a special variable that refers to the executing object.
Constants in Ruby start with a capital letter, for example, "Encoding". In most languages, including Ruby, constants are usually written in all uppercase letters. They should be assigned a value at most one time. After their initial assignment constants should remain immutable. In the current implementation of ruby, reassigning the value of a constant generates a warning message but not an error message. Ruby will let you change the value of a constant, with a only warning.
"100 pennies" "100 pennies" Dollar = "ten dimes" (irb):2: warning: already initialized constant Dollar (irb):1: warning: previous definition of Dollar was here "ten dimes" # --> Ruby warns me that the constant is already defined and should not be changed Dollar "ten dimes" # --> Although I shouldn't be able to do this, Ruby lets me reassign the Dollar constantDollar =
There are several pre-defined global variables in Ruby. These variables are useful for obtaining information about the current environment. Global variables are denoted with the dollar sign character ( $ ).
|$@||The location of the latest error|
|$_||The string last read by 'gets'|
|$.||The line number last read by the interpreter|
|$&||The string last matched by regex|
|$~||The last regex match, returned as an array|
|$=||The case-insensitivity flag|
|$/||The input record separator|
|$\||The output record separator|
|$0||The name of the currently running ruby script|
|$*||The command line arguments used to invoke the script|
|$$||The Ruby interpreter's process ID|
|$?||The exit status of last executed child process|
In this chapter you learned what a variable is, a pointer used to reference an object. Variables can have different scopes, which is where in the application they are accessible from.