Reputation: 1779
Suppose there is a model user.rb
. And I have a method define firstname
.
def firstname
shipping_address.try(:firstname)
end
def firstname
shipping_address && shipping_address.firstname
end
In both cases we are trying avoid unwanted exceptions. Is that what try is being used for?
Upvotes: 2
Views: 58
Reputation: 4653
As @dharam already said, the #try
method is a Rails method and &&
is plain ruby. The source code of it is pretty straightforward. But no they are not the same since as @sawa already said - &&
the operation cancels if an expression is nil
of false
.
Here the source code (#try
, without bang, uses this method):
def try!(*a, &b)
if a.empty? && block_given?
if b.arity == 0
instance_eval(&b)
else
yield self
end
else
public_send(*a, &b)
end
end
Upvotes: 0
Reputation: 168179
No.
&&
cancels further application of any expression following it when it is preceded by a falsy value. When the following expression is not executed, the return value is the value preceding &&
, i.e., either false
or nil
.
try
evaluates all arguments that are meant to be passed with the method in question, and cancels the application of the method when it is not defined. When the method call is not performed, the return value is nil
.
Upvotes: 3
Reputation: 14635
Yes it does the same in this very example, however since ruby 2.3 we have a new operator for this, called "safe navigation operator":
def firstname
shipping_address&.firstname
end
Upvotes: 1
Reputation: 6438
In essence, Yes.
Remember, it is added by rails
. So it will not work in plain ruby
projects.
Refer to Object#try for more info.
Upvotes: 0