From: Mark Sparshatt Date: 2004-05-20T05:53:23+09:00 Subject: Re: Zero is true ... whoda thunk? Jamis Buck wrote: > Steven@ruby-lang.org wrote: > >> Jamis Buck writes: >> >>> I'm SO glad that Ruby forces you to compare numbers explicitly, >>> instead of implicitly converting to bool. It makes code that much >>> more readable. >> >> >> >> It doesn't, though. This code will always print "foo": >> a = SomethingReturningANumber() >> if (a) # Probably meant to say "a != 0", or maybe "a == 0" >> puts "foo" >> end >> I think it _should_ force you to compare numbers explicitly -- >> comparisons >> should raise exceptions if passed anything other than booleans. But >> it's >> too late for such a change. >> -- >> Steven >> "No egg nog! In fact, no nog, period!" > > > Sorry -- I mispoke. My "force" I meant that Ruby requires you to do > explicit numeric comparisons for your conditions to work correctly, > not that it actually enforces that programming practice. You're right, > though. It would be nice if Ruby enforced that. > The problem with this there are a number of methods which return a numeric value of true and nil for false. e.g. the =~ operator returns the position of the substring that matches the regexp, or nil if it fails to match. If either you disallowed numeric values, or made zero a false value, in a boolean context then this behaviour would have to change to allow if(/abc/ =~ "abc") ... end -- Mark Sparshatt