What is different from || and salvation?

Is there a difference between using the || operator and rescue in Ruby?

Say:

 b = A.value || "5" b = A.value rescue 5 

where object A does not have a value method.

+4
source share
3 answers

|| is a logical or operator (remember that in Ruby, nil and false are evaluated as false, in a boolean context):

 nil || 5 # => 5 false || 5 # => 5 4 || 5 # => 4 

rescue intended to catch exceptions:

 fail 'bang' rescue 5 # => 5 'bang' rescue 5 # => "bang" nil rescue 5 # => nil 

In your examples, given that A not responding to value :

 A.value # NoMethodError: undefined method `value' ... b = A.value || 5 # NoMethodError: ... b # => nil b = A.value rescue 5 b # => 5 

Now suppose A.value returns nil :

 A.value # => nil b = A.value || 5 b # => 5 b = A.value rescue 5 b # => nil 
+9
source

|| is an or operator. Your first line reads:

Set the value of b to A.value; if not b (that is, b is nil or false), then set it to line "5".

Salvation allows you to recover due to exceptions. Your second line reads:

Set the value of b to A.value. If A.value throws an exception, ignore the problem and set b to 5 instead.

For an object A without a value method, the first line will crash the application.

For an object A whose value method returns nil, the second line will set b to nil.

+8
source

Besides what others have already told you, another difference is that || is an honest operator, and inline rescue tantamount to saving StandardError , which is due to the fact that various style manuals passionately frown . In other words, inline rescue is an obscene hack that should not be used too often in production code. Use the well-dressed begin ... rescue ... else ... ensure ... end .

+2
source

Source: https://habr.com/ru/post/1485568/


All Articles