开发者

Make FalseClass behave like TrueClass with meta programming

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 sugg开发者_JS百科estion:

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜