How to check if a Ruby object is a Boolean

前端 未结 9 1019
迷失自我
迷失自我 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条回答
  •  萌比男神i
    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
    

提交回复
热议问题