String interpolation vs String concatenation in Ruby


#1

1. family.each { |x, y| puts "#{x}: #{y}" }
2. family.each { |x, y| puts x + ": " + y }

In lesson number 10 both answers are accepted. Example 1 seems like more typing. Is there an advantage / benefit to using this format instead of Example 2?


#2

Here's the answer to your question:

http://stackoverflow.com/a/10076632/2675672

To quote:

Whenever TIMTOWTDI (there is more than one way to do it), you should look for the pros and cons. Using "string interpolation" (the second) instead of "string concatenation" (the first):

Pros:

  • Is less typing
  • Automatically calls to_s for you
  • More idiomatic within the Ruby community
  • Faster to accomplish during runtime

Cons:

  • Automatically calls to_s for you (maybe you thought you had a string, and the to_s representation is not what you wanted, and hides the fact that it wasn't a string)
  • Requires you to use " to delimit your string instead of ' (perhaps you have a habit of using ', or you previously typed a string using that and only later needed to use string interpolation)

Written by: Phrogz And as one comment (by Dominik Honnef) notes:

String concatenation, in this example, has to create 3 strings in total, while string interpolation only creates one

Hope it helps! :smiley: