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??
Ruby Literals
“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.
Conclusion
I learned %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.
Top comments (2)
I remember in early stages of learning Ruby being annoyed be these too, asking myself “Why would I want to use this??”.
And honestly, I think they’re pretty cool, but I still don’t quite understand when you should use these over just writing the array itself.
I’d love to know the appropriate/optimal use cases!
From what I've read, the main reason they exist is to give more readability and brevity. Seems the point is less commas and quotes. That being said, I've never made a habit of using them.
When I wrote this, I was thinking: more options means better, but in all honesty, I rarely take advantage of a lot of Ruby's alternatives. For example, I've never once used "detect" though I've used "find" a ton.
I tend to stick with what whatever I learn initially unless there's a good reason to change. Rethinking it now, I think I'm back to not liking the shorthand, lol.