Adrien Giboire Adrien Giboire - 2 months ago 12
Ruby Question

What is the difference between `try` and `&.` (safe navigation operator) in Ruby

Here is my code:

class Order < Grape::Entity
expose :id { |order, options| }
expose :time_left_to_review do |order, options|
order&.time_left_to_review # ERROR
expose :created_at { |order, options| order.last_transition.created_at }

# NoMethodError Exception: undefined method `time_left_to_review' for #<Order:0x007f83b9efc970>

I thought
is a shortcut for
but I guess I was wrong. May someone point me to the right direction regarding what I am missing?

I feel like it's not ruby related. Grape maybe? Though I don't get how it could be.

Answer Source

&. works like #try!, not #try.

And here is description of #try! (from documentation):

Same as #try, but will raise a NoMethodError exception if the receiving is not nil and does not implemented the tried method.

So basically it saves you from calling a method on nil, but if an object is presented it will try to call its method as usual.

The quote is from Rails Documentation, and so it's important to emphasize that Ruby does not provide #try, it's Rails, or more accurately ActiveSupport. While safe navigation operator &. is a language feature presented in Ruby 2.3.0.