How to check if a Ruby object is a Boolean

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

    Simplest way I can think of:

    # checking whether foo is a boolean
    !!foo == foo
    
    0 讨论(0)
  • 2020-11-30 19:39

    If your code can sensibly be written as a case statement, this is pretty decent:

    case mybool
    when TrueClass, FalseClass
      puts "It's a bool!"
    else
      puts "It's something else!"
    end
    
    0 讨论(0)
  • 2020-11-30 19:40

    I find this to be concise and self-documenting:

    [true, false].include? foo
    

    If using Rails or ActiveSupport, you can even do a direct query using in?

    foo.in? [true, false]
    

    Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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?

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

    This gem adds a Boolean class to Ruby with useful methods.

    https://github.com/RISCfuture/boolean

    Use:

    require 'boolean'
    

    Then your

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

    will work exactly as you expect.

    0 讨论(0)
提交回复
热议问题