Safe navigation operator in Ruby

Tram Ho

Since version 2.3.0 onwards, the Ruby language has added a very interesting navigation (&.) Operator. This operator has been in C # and Groovy for a long time with slightly different syntax -? .. So what does it do?

Situation

For example, in the database, we have an Account table and a Owner table that have 1 to 1 relationships. Suppose we have an account object and want to retrieve the address information of that account through the owner so that we do not encounter errors, we often write the following:

This way is really wordy and confusing to the reader. That is also one of the reasons that ActiveSupport is included with the try method, we can rewrite the code to be more concise as follows:

These two ways work similarly. This facility shall return address if N address of owner (returns nil if address is nil ), or returns false if owner is false

Use safe navigation operators (&.)

We can rewrite the above example with the safe navigation operator as follows:

Without the above two examples, the syntax seems a bit confusing, but the code looks a lot cleaner.

For example

In this example, I will compare the three above.

With the above explanation it seems the output we can foresee. But what if owner is false ?

The first surprise is the syntax &. just ignore nil but realize false , it is not exactly equivalent to the syntax s1 && s1.s2 && s1.s2.s3

What happens if exists owner but no address

Unfortunately, the try method does not check if the object responds to the given method. To be more rigorous we use the try!

Risk

Be careful when using the & . operator & . and check the nil values. Consider the following example:

In the last example, it’s quite confusing because nil&.nil? should return true . However that is a note

Array # dig and Hash # dig

An additional method is #dig , instead of writing a piece of code like this:

We can handle it more simply with Hash#dig

Epilogue

For a dynamic language, the handling of nil values ​​is quite tricky, so the addition of safe navigation operators and dig methods are necessary.

Refer

http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

Share the news now

Source : Viblo