Is there any difference between using the ||
operator and rescue
in Ruby?
Say:
b = A.value || "5"
b = A.value rescue 5
where the object A
does not have value
method.
Is there any difference between using the ||
operator and rescue
in Ruby?
Say:
b = A.value || "5"
b = A.value rescue 5
where the object A
does not have value
method.
||
is the boolean or operator (keep in mind that in Ruby, only the values nil
and false
evaluates to false, in boolean context):
nil || 5
# => 5
false || 5
# => 5
4 || 5
# => 4
rescue
is for exception catching:
fail 'bang' rescue 5
# => 5
'bang' rescue 5
# => "bang"
nil rescue 5
# => nil
In your examples, given that A
do not respond to value
:
A.value
# NoMethodError: undefined method `value' ...
b = A.value || 5
# NoMethodError: ...
b
# => nil
b = A.value rescue 5
b
# => 5
Now suppose that A.value
returns nil
:
A.value
# => nil
b = A.value || 5
b
# => 5
b = A.value rescue 5
b
# => nil
The ||
is an or
operator. Your first line reads:
Set b to A.value; if not b (i.e. b is nil or false), then set it to the string "5".
Rescue lets you recover from exceptions. Your second line reads:
Set b to A.value. If A.value raises an exception, ignore the problem and set b to 5 instead.
For an object A with no value method, the first line will crash the app.
For an object A whose value method returns nil, the second line will set b to nil.
Apart from what others already told you, one more difference is, that ||
is an honest operator, while inline rescue
is tantamount to rescuing StandardError
, which is someting that various manuals of style passionately frown upon. In other words, inline rescue
is an indecent hack, that should not be used too frequently in production code. Use decently dressed begin ... rescue ... else ... ensure ... end
statement instead.