Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation of multiple conditions

Tags:

ruby

I have a quick question :

In ruby, If I write

def test
  foo && a  == b && c == "bar"
end

if foo is null or false, will it keep evaluating the rest of the expression ?

Does it change anything if I do this instead

def test
  a == b && c == "bar" if foo
end

thanks a lot

like image 958
Mike W Avatar asked Sep 20 '25 00:09

Mike W


1 Answers

Theory

&& is a lazy operator, just like ||.

It means that in a && b, if a is false or nil, Ruby won't bother to check b because a && b will be false/nil anyway.

This behaviour is actually desired, because it saves time and could avoid NoMethodErrors.

if a && method_which_requires_a_non_nil_parameter(a)
  # ...
end

method_which_requires_a_non_nil_parameter wouldn't be called at all if a is nil.

or :

x = x || long_method_to_calculate_x

is often used for caching, more often written as :

@x ||= long_method_to_calculate_x

Answer

def test
  foo && a  == b && c == "bar"
end

The rest of the expression won't be evaluated if foo is nil or false : a, b, c could even be undefined without raising a NameError.

def test
  a == b & c == "bar" if foo
end
  • If foo is truthy, the results will be exactly the same.

  • If foo is nil or false, the 2 equalities won't be evaluated, just like with the first example. But :

    • If foo is nil, both test will return nil.

    • If foo is false, first example will return false, second example will return nil.

like image 169
Eric Duminil Avatar answered Sep 23 '25 01:09

Eric Duminil