DEV Community

Cover image for Safe Navigation Operator

Safe Navigation Operator

leighad profile image Leigha ・2 min read
Photo by Zumberto _ from FreeImages

We can't function without operators in any language, and sometimes working with them can be a bit confusing. But, did you know that there are some lesser known operators in Ruby that can make your life easier?

In this post I would like to explore the Safe Navigation Operator a bit further.

Lately I have been going through old projects to refactor, clean up my code, and get things live. I have been noticing many places where this smooth operator would have been useful.

What exactly does it do?

The Safe Navigation Operator returns nil if a method is called on a nil object.

Why should we care?

Well, it is best to avoid throwing errors at your users. It's not very nice!

Let's take a look at a quick example:

    patch '/pizzas/:id' do
        @pizza = Pizza.find_by(id: params[:id])

        if @pizza && @pizza.user == current_user
            if @pizza.update(params[:pizza])
                redirect to "/pizzas/#{}"
                erb :'/pizzas/edit'
            redirect to "/pizzas"
Enter fullscreen mode Exit fullscreen mode

In the snippet above, I am checking to see if there is indeed an instance of the Pizza class found by id, and if there is, does that instance's user match the current user?

    if @pizza && @pizza.user == current_user
Enter fullscreen mode Exit fullscreen mode

This works just fine, but it would be cleaner to write:

    if @pizza&.user == current_user
Enter fullscreen mode Exit fullscreen mode

Why not use .try? Well because that is provided by ActiveSupport as part of Ruby on Rails, which is awesome! However if you wish to remove this dependency, just use the Safe Navigation Operator instead of .try.

Discussion (0)

Editor guide