4

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.

4

3 回答 3

9

|| 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
于 2013-06-11T08:04:54.430 回答
8

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.

于 2013-06-11T07:29:26.343 回答
2

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.

于 2013-06-11T09:52:53.837 回答