I want to do this
lol = Klass.new(values)
unless lol
print "false"
end
lol.other_method # it is not nil or false, it is a Klass instance!
But lol, in this case, is not nil or false, but an object who can act as a false based on some internal value. I have this alternative
lol = Klass.new(values)
unless lol.to_bool
print "false"
end
But it is ugly IMHO.
I was thinking in extend the FalseClass or play with == but without success. Any Ideas?
Unfortunately, this is not possible.
This is one of those annoying cases where Ruby is not object-oriented. In OO, it must be possible for one object to simulate another (in fact, depending on whom you ask, this is the very definition of OO – remember that OO came out of simulation), but it is not possible to build an object which simulates
false.This is because, in Ruby, conditional control structures are baked into the language and don’t translate into message sends, whereas in other OO languages they are just regular message sends (or at least translate into message sends, just like
forin Ruby translates intoeach). For example, in Smalltalk, Booleans are actually implemented using the Church encoding of Booleans you know from Lambda Calculus, and translated to Ruby they look a bit like this:And
TrueClassis just the mirror image:And then, instead of something like
You would have
That way, you can easily create an object which simulates
falsesimply by implementing the respective methods.In other cases, where some object really absolutely must be an instance of a specific class and not just speak the correct protocol, Ruby provides an escape hatch. For example, if a method really requires an
Arrayas an argument, then it will first try to callto_aryto at least give you a chance to convert your object into anArray. The same goes forto_str,to_int,to_proc,to_floatetc. But there is no equivalentto_boolprotocol.