Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make FalseClass behave like TrueClass with meta programming

Tags:

ruby

This is theoretical question: is it possible to change FalseClass behavior to act like TrueClass? It is possible to override to_s, xor, &, | behavior but that is not enough.

If you like Test Driven Development, follow my colleague's suggestion:

puts "false is new true!" if false
puts "never happens" if true

assert false

Asserts won't work, would it? Is it possible to pass the test successfully?

like image 664
Edvinas Bartkus Avatar asked May 05 '10 09:05

Edvinas Bartkus


2 Answers

It is not possible. One way to think about it is that there is no method Object#truthiness? that could be redefined.

In Ruby MRI, the truthiness test is the RTEST macro that is hardwired to mean anything but Qfalse and Qnil, the two constants corresponding to false and nil. You would have to change this to redefine what is "truthy" or not.

like image 70
Marc-André Lafortune Avatar answered Sep 18 '22 08:09

Marc-André Lafortune


It is impossible, at least in the official Ruby implementation, as true and false logic is deep in the C parts (Qtrue and Qfalse). Making the assert pass would work, though, by overwriting assert. Also, you could use something like ruby2ruby to parse out all values, but than true would still not behave like false and statements like ![] would still return true. Also note that all other objects also behave like true in if statements and akin.

like image 35
Konstantin Haase Avatar answered Sep 18 '22 08:09

Konstantin Haase