Step 9: Variables
Okay, so now we know about a few types of data, and a few ways to manipulate them. However, something very fundamental is still missing. What if we want to evaluate the expression
12 ** 2, and print the result 3 times?
puts(12 ** 2) puts(12 ** 2) puts(12 ** 2)
This seems a bit repetitive, and if you remember, programming is all about automation. If something seems repetitive while you’re writing a program, odds are there is a better way to do it. In this case, we are asking the computer to do the same calculation three times. This might not seem like a big deal now, but what if the calculation was a lot more complicated and took the computer 30 seconds to evaluate, and we want to print the result 100,000 times? Now it seems like our program would be a lot faster if we could perform the calculation one time, save the result, and then print it as many times as we want.
number = 12 ** 2 puts(number) puts(number) puts(number)
Here, we saved the result of
12 ** 2 in a variable called
number, and then printed out number 3 times. In this example, we only had to perform the calculation once instead of three times.
In Ruby, variables can be named using letters and numbers, but must start with a lowercase letter. Also, by convention in Ruby if you want to call your variable something with multiple words, you use an underscore to separate the words.
three_hundred = 10 * 10 * 3 puts(three_hundred)
Ruby also allows us to change the values of our variables throughout our programs.
number = 8 puts(number) number = number + 1 puts(number)
Above we changed the value of the variable
number by adding
1 to the original value.