Last Updated: February 25, 2016
·
236
· CraigCottingham

Ruby silently concatenates adjacent string literals

Given this code,

a = [ "Hello" "world!" ]
p a.size

what will the output be?

Your immediate answer is likely to be "2". (Unless you paid attention to the title of this protip.) However, it will be "1". Go ahead and try it in irb. I'll wait.

The Ruby parser automatically concatenates adjacent string literals. They don't have to have the same kind of quote characters, and interpolation is still applied.

p "Hello " 'world!'
s = 'world'
p "Hello " "#{s}!"

This is documented behavior for the Ruby parser, which means it won't even generate a warning.