How to check if a Ruby object is a Boolean

前端 未结 9 976
迷失自我
迷失自我 2020-11-30 18:57

I can\'t seem to check if an object is a boolean easily. Is there something like this in Ruby?

true.is_a?(Boolean)
false.is_a?(Boolean)

Ri

相关标签:
9条回答
  • 2020-11-30 19:44

    As stated above there is no boolean class just TrueClass and FalseClass however you can use any object as the subject of if/unless and everything is true except instances of FalseClass and nil

    Boolean tests return an instance of the FalseClass or TrueClass

    (1 > 0).class #TrueClass
    

    The following monkeypatch to Object will tell you whether something is an instance of TrueClass or FalseClass

    class Object
      def boolean?
        self.is_a?(TrueClass) || self.is_a?(FalseClass) 
      end
    end
    

    Running some tests with irb gives the following results

    ?> "String".boolean?
    => false
    >> 1.boolean?
    => false
    >> Time.now.boolean?
    => false
    >> nil.boolean?
    => false
    >> true.boolean?
    => true
    >> false.boolean?
    => true
    >> (1 ==1).boolean?
    => true
    >> (1 ==2).boolean?
    => true
    
    0 讨论(0)
  • 2020-11-30 19:45

    So try this out (x == true) ^ (x == false) note you need the parenthesis but this is more beautiful and compact.

    It even passes the suggested like "cuak" but not a "cuak"... class X; def !; self end end ; x = X.new; (x == true) ^ (x == false)

    Note: See that this is so basic that you can use it in other languages too, that doesn't provide a "thing is boolean".

    Note 2: Also you can use this to say thing is one of??: "red", "green", "blue" if you add more XORS... or say this thing is one of??: 4, 5, 8, 35.

    0 讨论(0)
  • 2020-11-30 19:48

    There is no Boolean class in Ruby, the only way to check is to do what you're doing (comparing the object against true and false or the class of the object against TrueClass and FalseClass). Can't think of why you would need this functionality though, can you explain? :)

    If you really need this functionality however, you can hack it in:

    module Boolean; end
    class TrueClass; include Boolean; end
    class FalseClass; include Boolean; end
    
    true.is_a?(Boolean) #=> true
    false.is_a?(Boolean) #=> true
    
    0 讨论(0)
提交回复
热议问题