Ruby percent literals

A quick tour across the keyboard

David Faulkenberry

%q(Hello world!)
%q(Hello world!)

# "Hello world!"
# Can we interpolate?
%q(#{3 + 4})
# Can we interpolate?
%q(#{3 + 4})

# "\#{3 + 4}"
# Capitalize:
%Q(#{3 + 4})
# Capitalize:
%Q(#{3 + 4})

# "7"
%w(an array of strings)
%w(an array of strings)

# ["an", "array",
#  "of", "strings"]
%W(
  we can
  interpolate!
  #{3 + 4}
)

# ["we", "can",
#  "interpolate!", "7"]
%r(regex)
%r(regex)

# /regex/
# Too many parentheses?
regex = %r((\s[ar|c|ex|r]\w+))

# RuboCop says: use backslashes
# to join multi-line strings

"I hate regular expressions; \
they are just not cool"
.match(regex).captures.join
# Too many parentheses?
regex = %r((\s[ar|c|ex|r]\w+))

# RuboCop says: use backslashes
# to join multi-line strings

"I hate regular expressions; \
they are just not cool"
.match(regex).captures.join

# " regular expressions are cool"
# Too many parentheses?
regex = %r((\s[r|ex|ar|c]\w+))

# RuboCop says: use backslashes
# to join multi-line strings

"I hate regular expressions; \
they are just not cool"
.match(regex).captures.join

# " regular expressions are cool"
%i(an array of symbols)

# [:an, :array,
#  :of, :symbols]
%I(an array of
#{%w(interpol ated).join}
symbols)

# [:an, :array, :of,
# :interpolated,
# :symbols]
%s(a string symbol)

# :"a string symbol"

# Haven't found a
# real use here
%x(echo "Hello world!")

# "Hello world!\n"

# Last but not least,
# this one scares me

Want a helpful mnemonic for the Ruby percent literals?

Want a helpful mnemonic for the Ruby percent literals?

Ruby

/\s[r|ex|a|co]\w*/

Want a helpful mnemonic for the Ruby percent literals?

Ruby

Idioms

/\s[r|ex|a|co]\w*/
[:create, :update]

Want a helpful mnemonic for the Ruby percent literals?

Ruby

Idioms

Will

/\s[r|ex|a|co]\w*/
[:create, :update]
 ["word", "list"]

Want a helpful mnemonic for the Ruby percent literals?

Ruby

Idioms

Will

Sometimes

/\s[r|ex|a|co]\w*/
[:create, :update]
 ["word", "list"]
 :"the weird one"

Want a helpful mnemonic for the Ruby percent literals?

Ruby

Idioms

Will

Sometimes

eXude

/\s[r|ex|a|co]\w*/
[:create, :update]
 ["word", "list"]
 :"the weird one"
  :(){ :|: & };:

Want a helpful mnemonic for the Ruby percent literals?

Ruby

Idioms

Will

Sometimes

eXude

Quirkiness

/\s[r|ex|a|co]\w*/
[:create, :update]
 ["word", "list"]
 :"the weird one"
  :(){ :|: & };:
"good old strings"

Ruby percent literals

By David Faulkenberry

Ruby percent literals

  • 797