If Ruby’s so Happy, What’s %w(a b c)
When I started learning Ruby, I came across this quote about 50 times:
I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language.
According to its creator, Yukihiro Matsumoto, the goal of Ruby is to make programmers happy. For me, that was mostly true. There’s very few reserved words to memorize, tons of useful, baked-in methods, parentheses are often optional. It is a really clean language — to learn and use.
However, every once in a while, I would come across something like this:
%w(a b c)
Usually, I would find something like this while I’m in the middle of a bug, skimming docs, looking for a quick solution. Usually time was an issue so if I came across the odd percentage notation, annoyed, I’d skip it and open a new tab.
I’d think something like: If Ruby’s so happy, then what the hell is this??
“A literal is a special syntax in the Ruby language that creates an object of a specific type.” [ 1.]
Everything in Ruby is an object. Strings, integers, arrays and everything else have a class that dictates their identity, state, and behavior. To create an instance of one of these objects from its class, we invoke it with a literal.
These odd looking
% signs are shorthand ways of invoking a literal. For example,
%w invokes an array of strings. It works like this:
%w(a b c) # [a, b, c]
%w(turtle cat different turtle) # [turtle, cat, different, turtle]
According to a post on Stack Overflow:
There are other % literals:
%r() is another way to write a regular expression.
%q() is another way to write a single-quoted string (and can be multi-line, which is useful)
%Q() gives a double-quoted string
%x() is a shell command
%i() gives an array of symbols (Ruby >= 2.0.0)
%s() turns foo into a symbol (:foo)
And there’s other notations too. Check this link for more literals.
%w isn’t some happiness obfuscating headache. It’s actually another way Ruby gives its user options. It’s honestly pretty nice. Hell yeah, Ruby.