How to check if a Ruby object is a Boolean

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

    No. Not like you have your code. There isn't any class named Boolean. Now with all the answers you have you should be able to create one and use it. You do know how to create classes don't you? I only came here because I was just wondering this idea myself. Many people might say "Why? You have to just know how Ruby uses Boolean". Which is why you got the answers you did. So thanks for the question. Food for thought. Why doesn't Ruby have a Boolean class?

    NameError: uninitialized constant Boolean
    

    Keep in mind that Objects do not have types. They are classes. Objects have data. So that's why when you say data types it's a bit of a misnomer.

    Also try rand 2 because rand 1 seems to always give 0. rand 2 will give 1 or 0 click run a few times here. https://repl.it/IOPx/7

    Although I wouldn't know how to go about making a Boolean class myself. I've experimented with it but...

    class Boolean < TrueClass
      self
    end
    
    true.is_a?(Boolean) # => false
    false.is_a?(Boolean) # => false
    

    At least we have that class now but who knows how to get the right values?

提交回复
热议问题