Reputation: 195
I'm working on this exercise on Codewars (https://www.codewars.com/kata/typer-dot-js/), and I'm having trouble writing a type checker for booleans.
Based on my understanding, booleans either return true or false. But I've also read a lot of people saying that every object in Ruby is a boolean except for nil. I tried writing the method in a bunch of different ways, but I'm just not getting it. Below are some of the tries.
class Typer
def self.is_boolean? input
input == true || false
end
def self.is_boolean? input
input.class == TrueClass || FalseClass
end
def self.is_boolean? input
input == nil ? false : true
end
Upvotes: 0
Views: 60
Reputation: 3523
Ruby does not have a built-in method to convert values to Boolean. That may be by design, as the only false values in Ruby are false and nil. All other values (empty string, empty array, empty hash, 0) are true. There, however, a "hack" that can be used to convert values to Boolean: it’s called "bang-bang" or "double-bang" and it consists of two Boolean negation operators, like this:
!!nil
=> false
!!false
=> false
!!""
=> true
!!0
=> true
!![]
=> true
!!{}
=> true
Upvotes: 0
Reputation: 122383
||
doesn't work as you expected. For example,
input == true || false
is testing if
input == true
is truthy, or if
false
is truthy. Note that the latter isn't testing input == false
. And that is your main misunderstanding.
Upvotes: 2