How to check if a Ruby object is a Boolean

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

提交回复
热议问题