If you seldom use Ruby percent (%) notation in daily work, here’s a
quick summary of what I picked up recently.
Delimiter allows any non-alphanum
You can use any non alpha-numeric character as delimiter:
1
2
3
4
| %(any alpha-numeric)
%[char can be]
%%used as%
%!delimiter\!! # escape '!' literal
|
Bracket pairs no need to escape
No need to escape bracket pairs, even when nested.
You can escape, but will need to escape both open and close bracket.
1
2
3
4
5
| %( (pa(re(nt)he)sis) ) #=> "(pa(re(nt)he)sis)"
%[ [square bracket] ] #=> "[square bracket]"
%{ {curly bracket} } #=> "{curly bracket}"
%< <pointy bracket> > #=> "<pointy bracket>"
%< \<this works as well\> > #=> "<this works as well>"
|
Modifiers for String, Regex, Array, Symbol, Shell command
We often use % notation to create String and Array literals. But it
also supports Symbol, Regex and shell command.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| %(interpolated string (#{ "default" }))
#=> "interpolated string (default)"
%Q(interpolated string (#{ "default" }))
#=> "interpolated string (default)"
%q(non-interpolated string)
#=> "non-interpolated string"
%r(#{ "interpolated" } regexp)i
#=> /interpolated regexp/i
%w(non-interpolated\ string separated\ by\ whitespaces)
#=> ['non-interpolated string', 'separated by whitespaces']
%W(interpolated\ string #{ "separated by whitespaces" })
#=> ['interpolated string', 'separated by whitespaces']
%s(non-interpolated symbol)
#=> :'non-interpolated symbol'
%x(echo #{ "interpolated shell command" })
#=> "interpolated shell command\n"
|
Here’s some % notation examples written in minitest in case you interested.