An Easy Way to Combine Words in Ruby

By Christopher Haupt

You can add together your variables and new line symbols in Ruby, but Ruby has a number of shortcuts for merging strings that enable you to easily combine words.

The first is called by a really fancy term: string interpolation. Don’t worry about that for now — just check out how you combine strings:

2.2.2 :011 > big_a = "#{a1}n#{a2}n#{a3}n#{a4}"
=>"   A   n  A A  n AAAAA nA     A"
2.2.2 :012 > puts big_a
   A
  A A
 AAAAA
A     A
=> nil

Instead of using the addition operator, you create one big string with double quotes, and use #{} inside that string. That special combination of symbols means that any variable inside the curly brackets will have its value put in that location of the string.

In this example, you took the variables a1, a2, a3, and a4 and had their values automatically placed inside the new string. Because you included the newline character, too, the resulting string ends up being exactly like the longer sequence of addition operators you used.