nil || false
returns false
and false || nil
returns nil
. Does anyone have an explanation for this?
相关问题
- What means in Dart static type and why it differs
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Notice: Undefined property - how do I avoid that m
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
||
returns the result of the last expression evaluated. If it evaluates the LHS and finds atrue
value, you get the LHS; otherwise, you get the RHS (no matter what that RHS might be).As the others pointed out,
||
first evaluates the expression on the left. If it is "true" (anything exceptfalse
ornil
), 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 thechronic
gem:That means: "if the
options
hash includes a:now
value, store that in@now
. Otherwise, fall back onChronic.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 tofalse
ornil
, 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:(That only works if you know that the return value of
do_something
will never befalse
ornil
!)You can also use
&&
to squeeze a "guard" expression on the same line as what it is "guarding":Which could replace:
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.