Simon Kröger
10/17/2006 8:00:00 PM
matt neuburg wrote:
> In Ruby, zero isn't false and there is no equivalent of the ?: operator
> with the middle term omitted. So e.g. I'd like to say [pseudo-code from
> some other language]:
>
> oneThing()?:otherThing()
>
> meaning, if oneThing is nonzero, return oneThing, else return
> otherThing. Now, I don't want to evaluate oneThing twice, so I've ended
> up with this:
Well, most of the time just ask ruby to do what you want:
oneThing.nonzero? || otherThing
--------------------------------------------------------------------------
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"]
--------------------------------------------------------------------------
cheers
Simon