String Interpolation
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?
"and
+is tedious
to_sseems redundant. Can't Ruby figure this out for us?
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!"
+, now we only have one string!
"... #{expression} ..."
expressionis automatically converted to a string!
", not
')
What questions do you have?