So much of the Ruby language is methods rather than syntax, so I expected to find %q
, %w
, etc., defined as methods in the Kernel
class
Programming Ruby mentions them in the chapter about strings.
Related to %q{}
and %Q{}
is %{}
which is the same as %Q{}
. Also, the delimiters "{}
" I show can be a matching pair of delimiters, so you could use []
, ()
, etc. %q{}
is the same as using single-quotes to delimit a string. %Q{}
is the same as using double-quotes, allowing embedded strings to be interpolated:
%q{foobar} # => "foobar"
%Q{foobar} # => "foobar"
asdf = 'bar' # => "bar"
%q{foo#{asdf}} # => "foo\#{asdf}"
%Q{foo#{asdf}} # => "foobar"
Also, there is %w{}
which splits a string using whitespace, into an array. For instance:
%w[a b c] # => ["a", "b", "c"]
%w{}
doesn't interpolate embedded variables:
%w[a b asdf] # => ["a", "b", "asdf"]
%w[a b #{asdf}] # => ["a", "b", "\#{asdf}"]
And %r{}
which defines a regular expression:
%r{^foo}.class # => Regexp
Finally there is %x{}
which acts like backticks, i.e. "``", passing the string to the underlying operating system. Think of it as "exec":
%x{date} # => "Fri Nov 26 15:08:44 MST 2010\n"
A lot of Ruby's ideas for these shortcuts come from Perl, only in Perl they use q{}
, qq{}
, qw{}
, qx{}
and qr{}
. The leading q
stands for "quote", and they are treated and documented as "quoting" operators if I remember right. Ruby's documentation needs to be expanded, and this particular set of tools could definitely use some help.