From: Claudio Jeker Date: 2006-02-09T08:35:08+09:00 Subject: Re: boolean annoyance On Thu, Feb 09, 2006 at 07:35:08AM +0900, Alexis Reigel wrote: > When I started using ruby I had exactly the same problem as you, porting > some c code to ruby that was checking some flags. I didn't get to the > solution myself, as I never ever thought of 0 being true. > But once you see the advantages of it you'll really appreciate that > convention. > In c you do: (flags & 0x01) > In ruby you do: (flags & 0x01 == 0) or (flags & 0x01).nonzero? > Or even nicer: flags[0x01] Does flags[0x01] work with any kind of mask. I thought that flags[3] would return the value of bit 3 and not the value of bit 0 and 1... and from the ruby reference Bignum#[] returns the nth bit a 0 or 1 and so your flags[0x01] would suffer the same way as (flags & 0x01). > > > Shortly there was a discussion about the same topic on this list ("nil > != []"). I'll cite two convincing postings: > > > matthew smillie.said: > > 0 *the integer* is only false by convention, and it's a convention > confined to programming, originating (unless I'm mistaken) from > languages which didn't define specific 'true' and 'false' logcial > values separate from integer math. 0's used in some logical notations > as a symbol for 'false', but it's unlikely that anyone familiar with > formal logic will tell you those 0's are the same 0's you get from "2 - 2". > > There's no doubt that the convention's been made very useful, but > there's really no logical basis for equating any particular symbol to > true or false truth values over any other. > I don't believe that 0 is originating from programming languages but actually came from the boolean algebra itself. In a binary domain it is natural to make 0 false. (a && !a == 0 or if converted into the set-theory doing a intersection of a set A and the complementary set !A results in the empty set which is normaly written as some kind of 0). OK doing set algebra in ascii sucks but I think it is parsable. > > > amrangaye said: > > One example of this that tripped me up today is the regular expression > match operator (=~), which returns (0-based) the index of a match, or > nil otherwise. If 0 was false, you couldn't do: > > if str =~ /^Hello/ > > OK this is a valid argument against changing behaviour because it would cause a major regression to existing scripts. I think I have to swallow this pill and change my coding stile for ruby. Doing binary protocols in ruby is a bit more challenging than expected. -- :wq Claudio