Names & Variables

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
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"
age “almost three”

Types of name

There are various different types of name in ruby:

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 = 5
age_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.

a = 1

a

a+1

a

a = a + 1

a

b = "hello"

b

c = b.capitalize

b

c

d = "hello"

e = d.capitalize!

d

e

name = "Dave"

f = "Hello #{name}! "

f

name = "Sarah"

f

f * 5

Extension (for those who finish early)

[Note: this exercise has a lot more to do with maths than programming. If you don’t get it don’t worry!]

Consider the expression

x = (2 + 5*x - x**2)/5
  1. Let x = 1.1
  2. Write x = (2 + 5*x - x**2)/5 and then evaluate this multiple times (by pressing up and then enter in irb)
  3. What happens? Can you explain why?
  4. Let x = 1 and do the same thing. What happens and why?


Prev | Next