An Introduction to the Safe Navigation Operator in Ruby 2.3.0

Safe Navigation

We’ve all done something like this before:

if @user && @user.appointment && @user.appointment.date
    // code here
end

In fact, if you’re like me (I’m guessing you are) you do this all the time. Can’t be throwing exceptions on something like this and I doubt you want 100 b/r/e blocks to handle every little case like this.

 

Though, if you did want to write 100 b/r/e blocks, it would look a little like this:


begin

    arbitrary_date_method(@user.appointment.date)

rescue => e

    //handle @user or @user.appointment or @user.appointment.date being nil

end

Maybe a bit cleaner than a long logic chain but it’s basically a glorified if statement anyways. This is fine here and there but I don’t think you’d want 100 of these. So…

 

Introducing the Safe Navigation Operator! A new feature in Ruby 2.3 that enables us to stop having to create these nightmarish logic chains if we want to check out some nested attributes. You may have heard of this already but if you haven’t, it’s so simple to use and makes an impact right away.

if @user&.appointment&.date
    //code here
end

That’s it, short and sweet. Now if any of the values in your chain return nil the entire statement will return nil instead of throwing an exception. You’ll be able to pull off some neat ternary operator setups too now that you won’t need this huge chain that ruins the succinctness of a good ternary statement.