开发者

What method is called to evaluate Fixnum equality? [duplicate]

开发者 https://www.devze.com 2023-04-08 12:13 出处:网络
This question already has answers here: if(!x) vs if(x==false) in ruby 开发者_开发问答 (3 answers)
This question already has answers here: if(!x) vs if(x==false) in ruby 开发者_开发问答 (3 answers) Closed 9 years ago.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消