%{..}
,%!..!
etc are same as %Q{}
construct, that means string interpolation will happen. Be careful that the construct %{..}
,%!..!
are not %q{..}
.
>> x = 5
=> 5
>> %q[#{x}] # interpolation will not happen
=> "\#{x}"
>> %[#{x}] # interpolation will happen
=> "5"
>> %Q[#{x}] # interpolation will happen
=> "5"
>>
The % Notation
There is also a Perl-inspired way to quote strings: by using % (percent character) and specifying a delimiting character, for example:
%{78% of statistics are "made up" on the spot}
# => "78% of statistics are \"made up\" on the spot"
Any single non-alpha-numeric character can be used as the delimiter, %[including these]
, %?or these?
, %~or even these things~
. By using this notation, the usual string delimiters "
and '
can appear in the string unescaped, but of course the new delimiter you've chosen does need to be escaped. However, if you use %(parentheses)
, %[square brackets]
, %{curly brackets}
or %<pointy brackets>
as delimiters then those same delimiters can appear unescaped in the string as long as they are in balanced pairs:
%(string (syntax) is pretty flexible)
# => "string (syntax) is pretty flexible"