Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use && ("and") as if in ruby?

Tags:

ruby

From some personal experimentation I've seen what seems to be a behavior of ruby "and"/"&&" that seems similar to an if statement.

  condition && action

seems to be doing the same as

  if condition
    action
  end

Are these equivalent?

like image 633
Matthias Michael Engh Avatar asked Mar 20 '26 10:03

Matthias Michael Engh


1 Answers

It's because && short-circuits.

Take a && b. If a evaluates to false, then the expression is false regardless of what b is, so to avoid wasting time b is not evaluated. b only needs to be evaluated if a evaluates to true.

There's a similar short-circuiting behavior for || ('or'). Can you work out what it is?

[edit]

As Holger Just just pointed out, when I say a "true" value in Ruby, I mean any truthy value, and when I mention a "false" value in Ruby, I mean any falsey value. That is, true and false are not the only truthy and falsey values in Ruby. In fact, every value in Ruby except nil or false is truthy, with only those two exceptions being falsey. Notice that the string "false" and the number 0 are not one of those two exceptions, so they are actually truthy.

We can now fully describe the behavior of a && b:

  • If a evaluates to a falsey value, then a && b returns the value of a, with b left unevaluated.
  • If a evaluates to a truthy value, then a && b returns the value of b, resulting in both a and b being evaluated.
like image 111
wlad Avatar answered Mar 23 '26 02:03

wlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!