Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here is my code:

class Order < Grape::Entity   expose :id { |order, options| order.id.obfuscate }   expose :time_left_to_review do |order, options|     byebug     order&.time_left_to_review # ERROR   end   expose :created_at { |order, options| order.last_transition.created_at } end  # NoMethodError Exception: undefined method `time_left_to_review' for #<Order:0x007f83b9efc970> 

I thought &. is a shortcut for .try 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.

like image 349
Adrien Avatar asked Aug 22 '17 19:08

Adrien


People also ask

What's the difference between try to and try and?

In most cases, try and is interchangeable with try to. But there are some contexts in which try and implies success (do try and behave) and others where try and is ironic and implies failure (try and make me move).

What is the difference between try and tries?

When someone tries to do something, you can refer to what they do as a try or an attempt. Try is normally used only in conversation and less formal writing. In formal English, you usually talk about an attempt. After a few tries they gave up.

Is it OK to say try and?

In summary: When try is used to mean "to make an attempt at" it's often followed by an infinitive phrase, as in "try to explain." A lot of people don't like it when and appears in place of the to: "try and explain." There is, however, nothing wrong with try and, and you should feel free to use it.


1 Answers

&. 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 provided by Rails, or more accurately ActiveSupport. The safe navigation operator (&.) however, is a language feature presented in Ruby 2.3.0.

like image 128
Danil Speransky Avatar answered Oct 13 '22 17:10

Danil Speransky