How can I avoid the truth in Ruby?

Is there any standard way to avoid being true in Ruby, or do I need to roll my own solution like

class FalseClass def to_bool self end end class TrueClass def to_bool self end end true.to_bool # => true false.to_bool # => false nil.to_bool # => NoMethodError 42.to_bool # => NoMethodError 

Background: I know that to_bool will contradict the resolving nature of Ruby, but I play with triple logic and want to avoid accidentally doing something like

 require "ternary_logic" x = UNKNOWN do_something if x 

I use ternary logic because I am writing a website parser for sharing photos (for personal rather than commercial use), and it is possible that some fields will be missing, and therefore it will not be known whether the place matches my criteria or not. However, I would try to limit the amount of code using triple logic.

+4
source share
3 answers

Cannot affect veracity or falsity in Ruby. nil and false are false, everything else is true.

This is a feature that appears every couple of years or so, but is always rejected. (For reasons that I personally do not consider compelling, but I'm not the one to call.)

You will have to implement your own logical system, but you cannot prevent anyone from using Ruby logical operators on an unknown value.

I reimplemented the Ruby logical system once , for fun and to show that this can be done. It is easy enough to extend this to threefold logic. (When I wrote this, I actually ran the conformance tests from RubySpec and ported them to my implementation , and they all passed, so I'm honestly sure that it matches the Ruby semantics.)

+9
source

You can use the redefined operator ! in 1.9 and idioms !! to redefine the truth.

Let there be veracity in Pythonesque:

 class Numeric def ! zero? end end class Array def ! empty? end end !![] #=> false !!0 #=> false 
+4
source

I also created my own logical system in Ruby (for fun), and you can easily redefine the truth: Note that if! / Else_if! / Else!

 # redefine truthiness with the `truth_test` method CustomBoolean.truth_test = proc { |b| b && b != 0 && b != [] } if!(0) { puts 'true' }. else! { puts 'false' } #=> false 

see: http://github.com/banister/custom_boolean

+1
source

All Articles