To code along, make sure your
irb session is still open
from the previous chapter, or you can open a new
from your command prompt:
$ irb irb(main)>
It is often helpful to save the results of an expression into a named variable, so that you can use it later.
Here's a quick example. Code along, making sure you type the code exactly as shown:
irb(main)> name = "Alice" => "Alice" irb(main)> "Hi, " + name => "Hi, Alice"
In the above example, we first assigned the text
a variable called
name. This is very similar to the memory
facility in your calculator, but we're allowed to have as many
variables as we want by giving them unique names.
Here are more examples of how to use variables:
irb(main)> sport = "Baseball" => "Baseball" irb(main)> color = "Purple" => "Purple" irb(main)> sport => "Baseball" irb(main)> color => "Purple"
irb will parrot back the value of a variable when asked.
Before we continue, we must mention a few very important rules:
favorite_words. It's easier to read than
You can assign a new value to a variable at any time. The old value is simply discarded:
irb(main)> lucky_number = 5 => 5 irb(main)> lucky_number = 10 => 10 irb(main)> lucky_number * 2 => 20
Here are some more examples for you to try:
PRO TIP: Use the up-arrow key to recall previous commands.
irb(main)> favorite_drink = "coffee" irb(main)> favorite_drink.capitalize irb(main)> favorite_drink + " cup" irb(main)> favorite_drink = "tea" irb(main)> favorite_drink.capitalize irb(main)> favorite_flavor = "mint" irb(main)> favorite_flavor + favorite_drink irb(main)> favorite_flavor + " " + favorite_drink