Ruby:
Interpolating a string
How to:
In Ruby, you wrap your variable or expression in #{}
and plunk it down where you want it in a double-quoted string. Like so:
name = "Jesse"
greeting = "Hey there, #{name}!"
puts greeting # => Hey there, Jesse!
You’re not limited to just variables; any Ruby code can go in there:
price_per_kg = 5
quantity = 2
puts "Your total is: $#{price_per_kg * quantity}" # => Your total is: $10
Remember, single quotes won’t work:
puts 'Hey there, #{name}!' # => Hey there, \#{name}!
Deep Dive
Back in the day, we’d concatenate strings and variables using +
or <<
, making things messy fast.
email = "user" + "@" + "example.com"
Enter string interpolation in Ruby, a more refined way to merge text with code. Ruby evaluates whatever’s inside #{}
and converts it to a string automatically. Consider the work it saves from converting and concatenating strings:
"pi is roughly #{Math::PI.round(2)}"
Ruby’s not unique; many languages have their own flavor of this handy feature. But caution: unlike some languages, Ruby strictly reserves this magic for double-quoted strings and certain other cases (like backticks and symbols). Single-quotes just spit out what’s inside them, curly braces and all.
See Also
- Ruby Documentation on syntax: Ruby Docs - Syntax
- A deeper look into string manipulation: Ruby-Doc.org - String