From: Florian Gross Date: 2005-03-29T03:24:46+09:00 Subject: Re: Modifying boolean values Farrel Lifson wrote: > Is it possible to somehow ducktype an object so that it behaves like a > boolean object (ie true or false)? Everything but nil and false is true so you can indeed create custom true values, but you will not be able to create custom false values. This logic is hard-wired via the RTEST() macro for performance reasons. Patching Ruby ought to be relatively simple (just change the macro to to a method call to #to_bool), however. > however creating an anonymous class doesn't seem to be allowed and > this affected the results of the original true instance (it now > returns "1" as well) which I'd prefer stayed untouched. There's always just one true, one nil and one false object and their meta-classes are TrueClass, NilClass and FalseClass respectively. > So is there a way to create an object that acts like a true or false > when in boolean expression but still be modified without changing the > true or false global objects? Or is there any function called in the > evaluation of boolean expresssions which would allow me to ducktype a > modified object? Unfortunately, there isn't in standard Ruby. The feature would as well be useful for doing full object proxies (WeakRefs to false or nil currently misbehave). I suppose that you might be able to get this changed in standard Ruby if you find that the slowdown caused by changing the RTEST() macro is not too high. But I'm not sure if it is like that. Perhaps you could also special case true, false and nil so that they would not go through the RTEST() method call -- after all you already have one of those values in most cases.