So far we’ve used irb as a clever calculator, by working with values directly. Programming becomes a lot more powerful when you’re able to give values names.
A name is just something that you can use to refer to a value. In ruby you create a name by using the assignment operator, =.
age=5
You can change the value associated with a name at any point. It doesn’t even have to be the same type of value as the first value assigned to the name. Here we change the value associated with age to a string:
age="almost three"
Types of name
There are various different types of name in ruby:
local variables e.g. age: Local variables begin with a lower-case letter. They’re all we’ll be using for now.
constants e.g. PI: Any name that starts with a capital letter is deemed to be a constant. Ruby will complain if you try to change its value at a later date.
instance variables e.g. @name: Instance variables start with a single @ sign. They’re used to store values inside objects. More later.
class variables e.g. @@count: Class variables start with two @@ signs. They’re used to store values relevant to a set of objects. More on this later too.
global variables e.g. $last_error: Global variables start with a $ sign. They’re available anywhere in your program. Relying on global variables is normally a bad idea.
For the moment, we will just be using local variables. The important thing to take from the above list is that local variables must start with a lower-case letter.
String interpolation
String interpolation is a way of taking a variable and putting it inside a string.
To write a string in ruby you can either use ' or ".
string1='hello'string2="hello"
In the code above, string1 and string2 are exactly the same. The difference between ' and " is that " allows you to do string interpolation:
age=5age_description="My age is #{age}."#=> "My age is 5."
Any ruby expression inside the #{ } will be evaluated and inserted into the string. Here we gave it the variable age, which points to the value 5. As 5 is a value it evaluates to itself, so 5 is inserted into the string.
Exercise
For each of the following ruby expressions, try to predict what they will evaluate to. Check if you’re right in irb.