Last Updated: September 09, 2019
·
17.04K
· cachedout

Elegantly check for boolean type in rails

As a junior rails developer one of the first things that struck me as counter-intuitive was that I couldn't simply check for a boolean type in the same way I would any other class.

While I could ask a value if it is an integer in many ways:

value.integer?
value.is_a? Integer
#or synonymously 
value.kind_of? Integer

I could not in the same manner ask a value if it was a boolean:

value.boolean?
value.is_a? Boolean
value.kind_of? Boolean

Recently I was solving a larger problem and needed to know if my value was indeed a boolean - once the ticket reached code review a co-worker left a comment to the tune of
"I think this is clever.... it's surely not stupid, right? I haven't seen it before."

Personally the solution came quickly however due to his reaction I thought some people out there may benefit from what I think is quite the clever solution:

!!value == value

So what are your thoughts world? Clever; or stupid?

Another, more readable (therefore probably more ruby-esque) and equally effective solution is:

[true, false].include? value

Either of these would make a great util addition:

def is_boolean?(value)
   [true, false].include? value
end

alias_method(:is_bool?, :is_boolean?)
alias_method(:boolean?, :is_boolean?)