Ruby's Shovel Method: Digging Deeper

Heads up! This is not actually a deep dive šŸ˜¬

With everything going on in the world, I almost forgot how fun it can be to code in Ruby! I am not being sarcastic, its actually really fun!

What kind of fun?

Earlier, I was reviewing some code in a PR to Bridgetown, and I came across this change:

- static_template_files << "/Gemfile"
+ static_template_files.push "/Gemfile", "/package.json"

Whenever I see small method changes during code review, I find it a helpful mind exercise to consider whether the method actually needed to be changed since thereā€™s almost always a way in Ruby. More often than not, this leads me to my favorite type of Ruby: quirky, fun, and a bit magical.

You could even call it blursedā€¦šŸ¤”

And if we are really being honest, blursed Ruby is my favorite type of Ruby.

Array#<<

Commonly referred to as the ā€œshovel operatorā€, << is a method in Ruby that is commonly used to push an object onto an array, but you can shovel into strings as well.

For example:

%w[foo bar] << "baz"
#=> ["foo", "bar", "baz"]

Speaking of blursed Ruby, check out the example code in the docs for str << int.

TIL!

Today I /re(learned|membered)/ you can chain shovels! Not that you shouldā€¦.but just in case, know that you can.

The following is a blursed example of just that:

Blursed Ruby Shovel Code Screenshot

View gist

I realized I was grinning from ear to ear while writing this code. This code will run just fine if you paste it into IRB or Pry, emojis and all! A fun example of what you can do with Ruby, if you wanted to.

Back to code review

Just because you can do it doesnā€™t mean you should! The readability of swapping the shovel operator with the Array#push method is the right call in my opinion. The change got a green check of approval from me.

But, I couldnā€™t resist sharing my blursed example. Hopefully it makes you grin as well.

As I said at the beginning: itā€™s fun to write Ruby!

Happy coding!

Andrew Mason's profile image

Hey, I'm Andrew šŸ‘‹

I'm a senior product engineer at Podia, co-host of Remote Ruby and Ruby for All, and co-editor of Ruby Radar. You can explore my writing, learn more about me, or subscribe to my RSS feed.

Page Info

Published:
22 November 2020
Updated:
29 January 2022
Reading Time:
2 min read

Tags