Percent Notation
Percent Notation is a powerful and versatile Ruby feature. You can create strings that ignore interpolation. You can create strings that don't require escaping quotes. You can create a regex, a symbol, an array of symbols, and an array of strings.
String Delimiters
Percent notation can be as simple as creating strings with different delimiters to help avoid the tediousness of escaping quotes in some contexts.
> %<They say "I don't have to escape quotes!">
=> "They say \"I don't have to escape quotes!\""
You can use just about any character to wrap the string in this way:
> %\Face/Off\
=> "Face/Off"
> %:Con Air:
=> "Con Air"
> %?The Rock?
=> "The Rock"
> %{Snake Eyes}
=> "Snake Eyes"
You can take this to the extreme to write some very obfuscated code:
> %=what===%?what?
=> true
Percent notation is also an idiomatic way of creating arrays of strings and symbols, as well as a regex literal and symbol literal.
Percent Literals
There are a bunch of Percent Literal forms supported by Ruby. I'll mention a handful that are worth knowing about.
First, %q
creates a string that ignores interpolation in case you don't want #{...}
to be interpolated.
> %q:Look, no interpolation #{true}:
=> "Look, no interpolation #{true}"
Then there are some idiomatic, rubyist forms that you'll see commonly throughout codebases:
# a list of symbols
> statuses = %i[pending approved rejected]
=> [:pending, :approved, :rejected]
# a list of strings
> %w[Ruby Rails SQL Go]
=> ["Ruby", "Rails", "SQL", "Go"]
You can also use percent literls to create a regex with %r
:
> %r[\A.*@.*\z]
=> /\A.*@.*\z/
> _.match('[email protected]')
=> #<MatchData "[email protected]">
And don't forget about non-standard symbols with %s
:
> :Taco Bell
=> SyntaxError
> %s[Taco Bell]
=> :"Taco Bell"
> :"Taco Bell"
=> :"Taco Bell"