Using simple values as in introduction to Ruby article will get you bored soon. It is much more interesting to create names that can hold values and then use those names. These names we call "variables", because usually their content can be changes.

Variable nanes can starte with any lower~ or uppercase letter or underscore. They can contain lowercase, uppercase letters, digits, and underscores. Once we have assigned value to a variable we can use puts to print the content of the variable

We can also use the variables for other operations. For example to add them together:


a = 23
b = 19

c = a + b
puts c

$ ruby add_numbers.rb 

With this we can create a variable containing the name of the user, and then welcome that user by concatenating together two strings and the variable using + as string addition.


name = "Foo Bar"

puts "Hello " + name + ", how are you?"

$ ruby hello_name.rb 
Hello Foo Bar, how are you?

Interpolation or variable embedding

There is however another way to create the same result:


name = "Foo Bar"

puts "Hello #{name} how are you?"

Here we used the #{} construct to tell ruby, instead of the word 'name' it needs to take the content of the variable called 'name' and include that in the string.

Variable declaration in Ruby

In Ruby there is no need to declare a variable. It just has to appear in an assignment before it is used in any other expression.


x = 23
puts x

puts y
y = 19

$ ruby bad_variable.rb 
bad_variable.rb:5:in `<main>': undefined local variable or method `y' for main:Object (NameError)