From: Claudio Jeker Date: 2006-02-09T07:34:24+09:00 Subject: Re: boolean annoyance On Thu, Feb 09, 2006 at 01:16:26AM +0900, Matthew Moss wrote: > > there is one thing in ruby that annoys me most (at least for now). > > > > if 0 > > puts "true" > > end > > > > Yes, I know everything expect nil and false are true but that's probably > > the most illogic part of ruby. > > 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? The difference between NULL and nil is not that big. Did you ever try to do stuff like nil.split or nil.capitalize. In ruby you have two ways of living with nil. Either you catch exections created by nil access all over the place or check for access. This is similar to C the only difference is that in C you get a SIGSEGV. Sure 0 is an integer but it is a special one. If you do just if foo.to_i puts "true" end 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. > > > 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. > Course, I probably wouldn't hardcode 0x01 in any language, so: > This is only a simple example. My actual code does not use magic constants and it has nothing to do with actual problem. -- :wq Claudio