Substituting Variables into Strings

Problem

You want to create a string that contains a representation of a Ruby variable or expression.

Solution

Within the string, enclose the variable or expression in curly brackets and prefix it with a hash character.

number = 5 "The number is #{number}." # => "The number is 5." "The number is #{5}." # => "The number is 5." "The number after #{number} is #{number.next}." # => "The number after 5 is 6." "The number prior to #{number} is #{number-1}." # => "The number prior to 5 is 4." "We're ##{number}!" # => "We're #5!"

 

Discussion

When you define a string by putting it in double quotes, Ruby scans it for special substitution codes. The most common case, so common that you might not even think about it, is that Ruby substitutes a single newline character every time a string contains slash followed by the letter n (" ").

Ruby supports more complex string substitutions as well. Any text kept within the brackets of the special marker #{} (that is, #{text in here}) is interpreted as a Ruby expression. The result of that expression is substituted into the string that gets created. If the result of the expression is not a string, Ruby calls its to_s method and uses that instead.

Once such a string is created, it is indistinguishable from a string created without using the string interpolation feature:

"#{number}" == '5' # => true

You can use string interpolation to run even large chunks of Ruby code inside a string. This extreme example defines a class within a string; its result is the return value of a method defined in the class. You should never have any reason to do this, but it shows the power of this feature.

%{Here is #{class InstantClass def bar "some text" end end InstantClass.new.bar }.} # => "Here is some text."

The code run in string interpolations runs in the same context as any other Ruby code in the same location. To take the example above, the InstantClass class has now been defined like any other class, and can be used outside the string that defines it.

If a string interpolation calls a method that has side effects, the side effects are triggered. If a string definition sets a variable, that variable is accessible afterwards. It's bad form to rely on this behavior, but you should be aware of it:

"I've set x to #{x = 5; x += 1}." # => "I've set x to 6." x # => 6

To avoid triggering string interpolation, escape the hash characters or put the string in single quotes.

"#{foo}" # => "#{foo}" '#{foo}' # => "#{foo}"

The "here document" construct is an alternative to the %{} construct, which is sometimes more readable. It lets you define a multiline string that only ends when the Ruby parser encounters a certain string on a line by iteself:

name = "Mr. Lorum" email = <

Ruby is pretty flexible about the string you can use to end the "here document":

< "There once was a man from Peru Whose limericks stopped on line two "

 

See Also

Категории