From: James Edward Gray II Date: 2006-10-18T04:49:40+09:00 Subject: Re: ruby way to say this? On Oct 17, 2006, at 2:44 PM, Louis J Scoras wrote: > On 10/17/06, 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: >> >> (temp = oneThing()).nonzero? ? temp : otherThing() >> >> I don't like it. Is that culturally correct, or is there a ruby >> way to >> speak here, that I'm not thinking of? Thx - m. > > > Are you okay with adding an extra function call? > > How about: > > def if_zero(exp,alt) > exp == 0 ? alt : exp > end > > x = 0 > > if_zero( (x+=1) + 1, 7) # => 2 > if_zero( x-=1 , 8) # => 8 > > So your original would look like: > > # if_zero(one_thing, other_thing) If you change that to support a block, you can avoid evaluating other_thing unless it's needed: def if_zero(exp) exp.zero? ? yield : exp end if_zero(one_thing) { other_thing } James Edward Gray II