G

Useless Ruby Tricks

Ruby is a lovely language, with a lot of convenience functions that make it easy to read and pleasant to type. But over the years, it’s also added some wacky extra bits. Let’s explore the (rightfully) forgotten hallways of Ruby syntax.

% syntax

% syntax makes it easy to create arrays (%w(like this)), regexes (%r|match|), strings, and more. For a mostly-complete rundown, see this page. But did you know that pretty much any punctuation is allowed, not just parentheses or curly braces? Try it in irb:

> %|something| + %@wicked@ + %%this% + %*way* + %$comes$
"somethingwickedthiswaycomes"

Here’s the real kicker: spaces work as delimiters, too.

> % no  + %!way!
"noway"

String interpolation without curly braces

The standard way to do string interpolation inside a Ruby string is "#{this}". Most people don’t know that there’s even another way.

Instance variables, class variables, and globals don’t require the curly braces:

> @foo = "foo"
> @@bar = "bar"
> "#@foo #@@bar #$VERBOSE"
"foo bar false"

Confuse your coworkers today!

Got any more?

Do you have any more silly Ruby tricks? Let me know: @gabebw.