M
Matt Margolis
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?
Thank you,
Matt Margolis
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?
Thank you,
Matt Margolis