Variables and Variable Interpolation in Ruby
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:
examples/ruby/add_numbers.rb
a = 23 b = 19 c = a + b puts c
$ ruby add_numbers.rb 42
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.
examples/ruby/hello_name.rb
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:
examples/ruby/hello_name_embedded.rb
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.
examples/ruby/bad_variable.rb
x = 23 puts x puts y y = 19
$ ruby bad_variable.rb 23 bad_variable.rb:5:in `<main>': undefined local variable or method `y' for main:Object (NameError)
Published on 2015-10-06