← Back

Ruby's Shovel Method: Digging Deeper

Andrew Mason

Andrew Mason

Published Nov 21st, 2020


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!


Thanks for reading! You can discuss this post using one of the links below. Additionally, it would mean a lot if you shared this post with others!

Recent Posts