Ruby Safe Navigation Operator

I’ve been working on a new codebase lately and have been seeing an operator that was unfamiliar to me.

It is Ruby’s Safe Navigation Operator. It looks like this &. chained by subsequent methods. After looking into it, I realized that I had read about it in one of the Ruby Weekly newsletters a few years ago.

Most Ruby developers are probably familiar with the try method in Rails. What the try method does is it “tries” to execute a method on an object that may or may not have that method available to it. For example…

As one can see, try allows you to “try” methods that you’re not 100% confident will work on an object you’re invoking on. Ruby’s Safe Navigation Operator is exactly like Rails’s try method. You could write the above code in Ruby starting from Ruby 2.3.0 like this outside of the Rails ecosystem.

Now, I’m not sure how I feel about this operator being introduced in Ruby. I’ve never felt 100% sure if I liked the try method in Rails or not because anytime I used it in my code, I felt unconfident in my code. It made me feel like the code I was writing was weak, as if the variable I was invoking try on, I was designing my code in a way that it was difficult to predict what each of the variables was representing.

But, try was only available within the context of Rails and wasn’t available in Ruby land. Now, with the introduction of the Safe Navigation Operator, I have fear that this can be abused when writing pure Ruby programs. Maybe it can make your code more succinct when used correctly, but I can already see myself itching to abuse this when feeling lazy.

About the Author Chris Jeon

Software developer currently focusing on Android development.