From: Matt Margolis Date: 2007-10-10T01:07:35+09:00 Subject: Re: Make a class evaluate to false in boolean expressions Logan Capaldo wrote: > On 10/9/07, Matt Margolis wrote: > >> I want to have a class that always evaluates to false in boolean >> expressions. Is there a way to extend Ruby so that it evaluates an >> object of a class to false like false and nil? >> >> Example >> >> class AlwaysFalse >> end >> >> should_be_false = AlwaysFalse.new >> >> if should_be_false >> #I don't want this to ever run >> else >> #will always run >> end >> >> The use case for this is to have the concept of false but have it >> contain instance variables. You can't stick instance variables on >> FalseClass because it is a singleton and every use of false will >> overwrite the previous instance variable values. >> a = false >> a.name = "fish" >> b = false >> b.name = "ocean" >> #at this point in time a.name is equal to "ocean" and not "fish" like I >> want. >> >> This example may seem like an awful design decision but in the program I >> am writing it is important to have an interface like this to meet the >> requirements I have to code against. >> >> Is achieving this behavior as simple as redefining some operator methods >> like == or is this sort of behavior not possible in Ruby? >> >> > The latter. > > OTOH: > > class Object > def false? > false > end > end > > class FalseClass > def false? > true > end > end > > class YourClass > def false? > true > end > end > > if condition.false? > ... > end > > Kind of annoying if you forget the .false? though. A better thing to > do would be to figure out what you are trying to model by having > multiple "falsy" values with some state. > > >> Thank you, >> Matt Margolis >> >> >> > > I don't want to have to call .false? though. Ideally what I would like to be able to do is just use the object in boolean expressions like false. Anyone have any idea if this is at all possible? Matt Margolis