Ruby for the Newbie - Variables
(Page 3 of 4 )
Variables are storage units that hold data. The data ranges from numbers, to text (strings), to a multitude of other data. In order for a variable to work, you must name it (otherwise you cannot refer to it ) and place the data within it. Note that the data held in a variable can change, and so can the data in a constant (discussed later), unlike in other programming languages.
When naming a variable, there are several things to keep in mind. The basic convention for naming a variable is that if there is more than one word, separate them by using the underscore (example: my_variable). Typically variables are lowercase, start with a letter, and can contain letters, numbers, underscores, and capital letters. Any name you choose is fine so long as it follows those conventions and does not use one of Ruby's reserved words, shown in the table below:
BEGIN | END | _file_ | _line_ |
alias | and | begin | Break |
case | class | def | Defined? |
do | else | elsif | 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 |
The syntax for storing data in a variable looks like this:
first_name=James
last_name=Payne
title="Gorilla Lord"
This tells the program that the first variable is named first_name and to store the word "James," and so on. If we wanted to use the variable to, for example, list the name and title on a screen, we could do so this way:
puts first_name
puts last_name
puts title
This would display the following text:
James
Payne
"Gorilla Lord"
I could also do this:
puts first_name + last_name + title
Resulting in the string: James Payne "Gorilla Lord".
If we wanted to work with numbers and text, we could try the following.
Age=30
puts "I am" + String(age) + "years old!"
age=age -8
puts "I wish I was" +String(age) + "years old!"
This creates a variable named Age and stores the value of 30 in it. Then it takes that value, converts it to a string (more on data types later) and adds it to our sentence. Then, it takes that value, subtracts 8 from it, and adds it to the last sentence, giving us this final result:
"I am 30 years old!"
"I wish I was 22 years old!"
Interpolation of Variables
Another way to insert the value of a variable into a string is through interpolation.
age=30
puts "I am #(age) years old!"
This would display: "I am 30 years old!"
Next: Constants >>
More Ruby-on-Rails Articles
More By James Payne