Ruby Monstas


String Interpolation

Motivation

Consider this code:
puts "Hi! Please enter a number:"
number = gets
puts "Output: " + (2 * number.to_i).to_s + " Bye!"
Let's run it!
$ ruby gets.rb
Hi! Please enter a number:
43
Output: 86 Bye!
puts "Hi! Please enter a number:"
number = gets
puts "Output: " + (2 * number.to_i).to_s + " Bye!"
What's uncool about this code?
  • Typing
    "
    and
    +
    is tedious
  • to_s
    seems redundant. Can't Ruby figure this out for us?

String Interpolation

puts "Hi! Please enter a number:"
number = gets
puts "Output: " + (2 * number.to_i).to_s + " Bye!"

Let's rewrite the code using String Interpolation:

puts "Hi! Please enter a number:"
number = gets
puts "Output: #{2 * number.to_i} Bye!"

Another example:

puts "Hi! What's your name?"
name = gets.chomp
puts "Hi, #{name}!"
puts "Hi! Please enter a number:"
number = gets
puts "Output: #{2 * number.to_i} Bye!"
Note: We had 3 strings connected with
+
, now we only have one string!
Note: Syntax is
"... #{expression} ..."
Note: The result of
expression
is automatically converted to a string!
Note: String interpolation only works with double quoted strings (
"
, not
'
)

Additional Resources

Ruby For Beginners: String Interpolation

What questions do you have?