I thought that doing puts #{a} would result in the same output as puts a, but found this not to be the case. Consider:
irb(main):001:0> a = [1,2]
=> [1, 2]
irb(main):002:0> puts a
1
2
=> nil
irb(main):003:0> puts "#{a}"
12
=> nil
irb(main):004:0>
In the above example it doesn’t matter much, but it may matter when I want to print multiple variables on one line, such as (psudocode):
puts "There are #{a.size} items in the whitelist: #{a}"
Why is the output different here? Do they actually do different things, or have different semantics?
That’s because
"#{a}"calls the#to_smethod on the expression.So:
Update:
To elaborate,
putseventually calls#to_sbut it adds logic in front of the actual output, including special handling for arrays. It just happens thatArray#to_sdoesn’t use the same algorithm. (Seeputsdocs here.) Here is exactly what it does…