Reputation: 2333
I often face the situation when if condition A (for example [email protected]?
) is false
, condition B, when checked, can raise an error (for example @object.some_method -> undefined method 'some_method' for nil:NilClass
).
I tested it in console, but could't get some full data.
1) Is it safe to use and
/&&
when if first conditional is false
, second can lead into an error?
2) What about or
?
Upvotes: 0
Views: 62
Reputation: 1633
Second part of these lines will never be exected:
false && raise "this will never be raised"
true || raise "this will never be raised"
In your case, if you are using active support, you can do:
@object.try!(:some_method)
Upvotes: 1
Reputation: 13690
[email protected]? && @object.some_method
@object && @object.some_method
Both of the above are valid patterns in Ruby. You will not get the "undefined method for nil" error, because the expression to the right of the &&
is never evaluated if the expression to the left of it evaluates to nil
(or false
).
You can also accomplish this check using postfix if
or unless
:
@object.some_method if @object
or
@object.some_method unless @object.nil?
are both valid alternatives.
Regarding or
:
Using ||
(Rubyists generally avoid the keyword or
operator) will not protect you from the error, because when the expression on the left side of the ||
evaluates to nil
, the interpreter will actually continue on and attempt to evaluate the expression on the right side.
Upvotes: 2