nil || false and false || nil in ruby

2019-04-20 12:56发布

问题:

nil || false returns false and false || nil returns nil. Does anyone have an explanation for this?

回答1:

In Ruby, everything is an expression, and an expression will return the last value evaluated within it.

For both of your examples, the left side of the || expression evaluates to a falsy value, so Ruby then evaluates the right side, and returns it.



回答2:

As the others pointed out, || first evaluates the expression on the left. If it is "true" (anything except false or nil), it returns that. Otherwise, it evaluates the expression on the right, and returns it (no matter what it is).

This makes || useful for a lot more than just boolean tests. For example, I just used it the other day when writing some code for the chronic gem:

@now = options[:now] || Chronic.time_class.now

That means: "if the options hash includes a :now value, store that in @now. Otherwise, fall back on Chronic.time_class.now as a default". I'm sure you can think of lots of possible applications in your own programs.

&& is analogous: it first evaluates the expression on the left, and if it evaluates to false or nil, it returns that. Otherwise, it evaluates the expression on the right, and returns it (no matter what it is).

This means && is also useful for a lot more than just boolean tests. You can use it to squeeze two lines of code into one. For example:

do_something && do_something_else

(That only works if you know that the return value of do_something will never be false or nil!)

You can also use && to squeeze a "guard" expression on the same line as what it is "guarding":

message && send_message(message)

Which could replace:

unless message.nil?
  send_message(message)
end


回答3:

|| returns the result of the last expression evaluated. If it evaluates the LHS and finds a true value, you get the LHS; otherwise, you get the RHS (no matter what that RHS might be).



标签: ruby null