Learning Rails

February 3, 2007

The values returned by || and &&

Filed under: Ruby Language — joelg @ 7:45 am

Ruby has logic that appears to me…well…logical. I feel there’s a “groove” to thinking in Ruby. I’m not able to articulate it further, probably because I’m not that familiar yet with the language. But there’s something about the way things work in Ruby that makes sense to me. It’s taken me a lot of reading and playing in irb, but by experimenting, I’m starting to understand Ruby’s groove.

One example is the caparison operators for and (&&) and or (||). At first glance, there’s nothing really different about them. But, let the narrative in The Pick Axe Book sink in and I have an “a-ha” experience. “That’s why they do it that way!”.

Turns out, Ruby does only as much as it needs to do in order to return true and false. Take && , for example. && is true if both expressions are true. It’s false if one expression is false. So, if you end up with a statement

false && true

Ruby returns false, obviously. With ||, if the first expression is false, Ruby goes on to the second, which determines the value of the expression. In other words,

false || true

returns true. And,

true || false

returns true. Pretty straightforward stuff; it explains the common     idiom:

variable = expression || default value

But Ruby also has the value nil. Here’s where things get interesting. With &&, nil behaves much like false,

true && nil

returns nil. But with &&, Ruby only goes so far as the first expression if it finds it’s not true (in other words, nil or false). Eg:

nil && false

returns nil, NOT false. Conversely,

false && nil

returns false, NOT nil.

not true

returns false.

not false

returns true

not nil

returns true

Interesting, no? Most of the time, nil and false behave the same. The only exception is under the following three statements, which all return nil:

nil && true
true && nil
nil && false

Wacky, but true.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress