Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between || and rescue?

Tags:

ruby

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.

like image 788
TheOneTeam Avatar asked Nov 30 '22 21:11

TheOneTeam


2 Answers

|| 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
like image 78
toro2k Avatar answered Dec 22 '22 16:12

toro2k


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.

like image 37
Denis de Bernardy Avatar answered Dec 22 '22 15:12

Denis de Bernardy