From: Austin Ziegler Date: 2006-02-09T09:15:54+09:00 Subject: Re: boolean annoyance On 08/02/06, Claudio Jeker wrote: >> It's actually the most illogic part of languages like C that treat 0 >> as false. Believe me, having spent most of my programming life using >> C/C++ and being used to that, I make mistakes regularly whilst writing >> Ruby code. >> >> 0 is an integer and quite often a valid value. C's treatment of 0 as >> false is convenient in some situations but horribly inconvenient in >> others. Because if I'm expecting an integer and zero is a legal >> value, then you have to start playing around in your conditionals... >> "Okay, today any -1 is false"... or even at different levels than >> that. Part of the problem is that C doesn't have an actual NULL... >> NULL is just defined as zero. Overlap, explosions, crash and burn... > If you are inspecting a integer against nothing end everything is just > legal, why are you inspecting it? Sorry, but that doesn't work. If you have something that returns an integer value -- consider strtol(3). This can return *any* valid integer value, but if you get a 0, LONG_MAX, or LONG_MIN, you have to *then* check errno to see if the conversion was, in fact, successful. (And the conversion could be unsuccessful for any number of reasons.) Ruby's general approach is much better: either throw an exception or return +nil+ if you've got a non-useful value. I shouldn't have to second-guess what may be a valid value. > I expect of a language as cool as ruby to actualy use some #to_bool > converter to duck type the integer into the boolean domain. And from > the math point of view I expect that 0 is treated as false in boolean > context. In boolean algebra 0 is always used to indicate false if > numbers are used. But Ruby is *not* Boolean Algebra. And simply using "0" to represent false is a representation -- one could use "f", just as easily. This is what Ruby has done. Zero isn't a special number. It's just zero. >>> Because of this stuff like >>> >>> if flags & 0x01 >>> # do some stuff if flag is set >>> end >> There are alternatives.... In C/C++, this is what I would do because >> it is convenient. In Ruby, I might do: >> >> if (flags & 0x01).nonzero? > Wow. I was told that the cool thing about ruby is to write less code. > Side node: a & b is a boolean expression a bitwise boolean expression > but still boolean. It is not, in fact, a boolean expression. It is a bitwise expression. The only thing that makes it even remotely *close* to being boolean is its presence in an if statement. Otherwise, you wouldn't get the desired result when you really *do* want to do bitwise OR or AND operations. -austin -- Austin Ziegler * halostatue@gmail.com * Alternate: austin@halostatue.ca