From: Claus Spitzer Date: 2004-05-21T00:07:02+09:00 Subject: Re: Zero is true ... whoda thunk? On Thu, 20 May 2004 23:42:59 +0900, Carlos wrote: > > [Claus Spitzer , 2004-05-20 02.53 CEST] > > > > On Thu, 20 May 2004 09:47:07 +0900, Nicholas Van Weerdenburg > > wrote: > > > > > > nonzero? returned nil instead of false for me. Shouldn't it return false? > > > > 8< ----- snip ----- > > > > No. From the pickaxe: > > > > nonzero? num.nonzero? -> num or nil > > > > Returns num if num is not zero, nil otherwise. This behavior is useful > > when chaining comparisons: > > > > a = %w( z Bb bB bb BB a aA Aa AA A ) > > b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b } > > b � ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"] > > But why shouldn't it return false instead of nil? > > Well, it's just a matter of grammar. zero? could have been implemented as returning nil or or 0 (since 0 is true), but that's not as neat and tidy as true/false. On the other hand, nonzero? returns nil or the actual number, and nil/number is a better pair than false/number. From the programmer's view, it's neater to have false/true and nil/value pairs, and unless you do something like if num.nonzero? == false instead of if num.zero? then you won't really notice the difference. Cheers! -C