Many would say that the safe navigation operator (
&.) in Ruby is a drop in replacment for Rails’
#try. However I came across an interesting case where they are not the same.
thing = nil thing&.something > nil
thing = nil thing.try(:something) > nil
Seems pretty much the same right?
However what happens when the object receiving the message is not nil but does not respond to the message?
thing = Thing.new thing&.something > NoMethodError: undefined method 'something' for <Thing:0x0000>
thing = Thing.new thing.try(:something) > nil
Hopefully not something you’ll run into often, but definitely be aware of it. It makes the safe navigation operator not necessarily a drop in replacment.Tweet