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
&&
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With