158

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)

Right now I'm doing this and would like to shorten it:

some_var = rand(1) == 1 ? true : false
(some_var.is_a?(TrueClass) || some_var.is_a?(FalseClass))
1

9 Answers 9

153

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!

3
  • 1
    best answer by far, although I also liked foo == true or foo == false that somebody put in a comment. Commented Jun 10, 2016 at 20:53
  • 6
    I like this because it is less cryptic in intent than the !!foo == foo. Commented Nov 14, 2017 at 19:38
  • Downright pythonic! Definitely the most semantic answer here by far. Commented Dec 4, 2019 at 19:40
149

Simplest way I can think of:

# checking whether foo is a boolean
!!foo == foo
17
  • 6
    class X; def !; self end end ; x = X.new ; !!x == x #=> true
    – Alexey
    Commented Jun 7, 2012 at 12:08
  • 5
    Yes, that's called duck typing and a core principle of OOP. I think it's a feature. Commented Jun 19, 2012 at 16:41
  • 79
    Short doesn't necessarily mean simple. By which I mean, wtf is that? Commented Apr 11, 2013 at 22:00
  • 12
    Turns foo into a boolean, checks if that's the same as foo. Commented Apr 12, 2013 at 18:06
  • 13
    Note that double negation is considered bad style by some checkers (like RuboCop).
    – sschuberth
    Commented May 10, 2016 at 10:25
94

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
5
  • 2
    trying to do typecasting based on the current value.
    – HareSurf
    Commented Jun 12, 2010 at 10:45
  • 92
    'Why would you ever what that?' (and derivatives) is just one of the most annoying questions an engineer can make another :)
    – deprecated
    Commented Mar 27, 2014 at 14:20
  • 14
    +1 because I can use this in rspec like: expect(some_method?(data)).to be_a(Boolean)
    – Automatico
    Commented Oct 14, 2014 at 15:56
  • 3
    Other case when need to check type, is when you implement database adapter and need wrap strings with "quotes" but not numbers and booleans Commented Dec 30, 2016 at 18:19
  • I'd say that being able to check the type of a variable is such a fundamentally valuable thing for a programming language, and is super important when validating user input. The fact that it's not supported without these odd hacks is... confusing to me.. Doing some research it seems to be that Ruby's way of implementing dynamic typing means there is no way to derive the type. Javascript doesn't have this issue, so I guess there is some larger story behind this..
    – Seth
    Commented Oct 12, 2022 at 18:16
29

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
4
  • 6
    Simpler just to write self == true or self == false. Those are the only instances of TrueClass and FalseClass.
    – Chuck
    Commented Jun 12, 2010 at 18:50
  • @chuck that returns the same results except for Time.now.boolean? which returns nil. Any idea why?
    – Steve Weet
    Commented Jun 12, 2010 at 22:24
  • Defining a class check on self in the method is somewhat not oop. You should define two versions of boolean, one for TrueClass/FalseClass and one for Object. Commented Jun 13, 2010 at 19:41
  • 4
    The reason is that a bug in the version of Time#== in Ruby 1.8 causes a comparison to non-Time values to return nil rather than false.
    – Chuck
    Commented Jun 13, 2010 at 20:58
22

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
7

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
4

So try this out (x == true) ^ (x == false) note you need the parenthesis but this is more beautiful and compact.

It even passes the suggested like "cuak" but not a "cuak"... class X; def !; self end end ; x = X.new; (x == true) ^ (x == false)

Note: See that this is so basic that you can use it in other languages too, that doesn't provide a "thing is boolean".

Note 2: Also you can use this to say thing is one of??: "red", "green", "blue" if you add more XORS... or say this thing is one of??: 4, 5, 8, 35.

1
  • Why XOR? Why not OR?
    – Nakilon
    Commented May 28, 2019 at 18:45
2

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.

2
  • 1
    Checking something fundamental, such as whether an object is boolean should not require third-party gems. Commented Jun 23 at 16:37
  • @NikitaFedyashev I agree, but the language is what it is. If you find you need to check if a variable is Boolean often, you can either re-implement the gem yourself, or just use the gem. Commented Jun 24 at 17:18
-2

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.