I know that in Ruby, all numbers, including zero, evaluate to true when used in a conditional statement. However, what method is being called to perform this evaluation (see Ex. 2 below)? I thought it might be the == operator, but not so as they return opposite results.
Example 1: The equality method evaluates zero to false
>> puts "0 is " << (0 == true ? "true" : "false") 0 is false
Example 2: Yet zero alone evaluates to true, because it is not nil
>> puts "0 is " << (0 ? "true" : "false") 0 is true
They don't "evaluate to true" in the sense of being equal the object true
. All objects except nil
and false
are considered to be logically true when they're the value of a condition. This idea is sometimes expressed by saying they are truthy.
So, yes, testing equality uses the ==
operator. A bare 0
is truthy for the same reason 29
and "Hi, I'm a string"
are truthy — it's not nil
or false
.
0 == true # evaluates to false => ergo "false"
vs
0 # bare zero before the ? is evaluated using ruby truthiness and since it is not false or nil, "true" is returned
精彩评论