Chapter 4: Variables

It’s time to dive into various interesting features of Ruby. We’ll start with the most basic concept in programming: variables.

In real life, you assign names to things and people to identify them. Programming is not different. Instead of things and people, we have bits of memory, and we refer to them by something called a variable.

Why variable? because it’s not fixed. A variable can point to different things during the lifetime of a program.

You can think of a variable is a placeholder. This placeholder refers to some value.

For example, in the real world, the term name is a variable. It can refer to the value David, or it can refer to Yukihiro, depending on what value it’s assigned to.

In Ruby, you can create a variable and assign a value to it using the following code.

name = 'David'

The value on the right-side of the = (David) is assigned to the variable on the left-side (name). From now on, the variable name points to the word ‘David’, until you change its value.

You can also print variable’s value, using the print command (it’s a function, but we’ll learn about functions and methods later) we saw earlier.

print name  # David

Now run the program again. Ruby will print ‘David’ on the terminal.

$ ruby code.rb
David

Let’s change the name and print it again.

name = 'Japan'
print name  # Japan

You can also assign a number to a variable.

age = 30
amount = 1000

You are allowed to change a variable’s value by reassigning it.

amount = 2000

In Ruby, variable names are case-sensitive. Hence name is different from Name. The standard convention is to use all lower-case words for variable name, such as age, name, amount, etc.

If the variable contains multiple words, separate them with an underscore _, such as student_name or employee_count. This naming convention is also known as snake_case.

Next: Comments