How to check if a Ruby object is a Boolean

前端 未结 9 1015
迷失自我
迷失自我 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:40

    An object that is a boolean will either have a class of TrueClass or FalseClass so the following one-liner should do the trick

    mybool = true
    mybool.class == TrueClass || mybool.class == FalseClass
    => true
    

    The following would also give you true/false boolean type check result

    mybool = true    
    [TrueClass, FalseClass].include?(mybool.class)
    => true
    

提交回复
热议问题