0

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
    
seanreads
  • 447
  • 1
  • 4
  • 6

2 Answers2

2

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.

Chuck
  • 234,037
  • 30
  • 302
  • 389
0
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
Ransom Briggs
  • 3,025
  • 3
  • 32
  • 46
  • Can you be more specific about "ruby truthiness"? Where is this implemented in the language? For example, how would one override it just as one could override the == operator? – seanreads Sep 23 '11 at 15:48
  • http://stackoverflow.com/questions/3645232/how-can-i-avoid-truthiness-in-ruby – Ransom Briggs Sep 23 '11 at 15:55
  • Though I would not recommend overriding it, as you would get unexpected behavior in other people's code you depend on. – Ransom Briggs Sep 23 '11 at 15:56
  • Thank you! Yes, I understand that overriding is ill-advised when coding as usual. I'm looking at this for academic purposes, for the moment. – seanreads Sep 23 '11 at 18:04