0

I often face the situation when if condition A (for example !@object.nil?) 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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Joe Half Face
  • 2,303
  • 1
  • 17
  • 45

2 Answers2

2
!@object.nil? && @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.

user513951
  • 12,445
  • 7
  • 65
  • 82
  • It may be worth mentioning that this is called [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) – Stefan Dec 11 '15 at 11:24
1

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)
Thomas
  • 1,613
  • 8
  • 8