Why do not Booleans have a common class in Ruby?

2

Ruby does not have a class Boolean . I noticed that boolean objects are of specific classes depending on the value, see:

true.class  => TrueClass
false.class => FalseClass

Unlike other languages, such as C # and Java, where true and false are bool , Ruby is TrueClass or FalseClass .

This implies: if I want to check if an object is Boolean, I have to do something like:

def boolean?(value)
  [TrueClass, FalseClass].include? value.class
end

In this case, I see it as the only way to see if an object is of a boolean type. Otherwise, it would check only if an object is truthy or falsy.

!!nil #=> false
boolean?(nil) #=> false

!!"Olá!" #=> true
boolean?("Olá!") #=> false

!!false #=> false
boolean?(false) #=> true

!!true #=> true
boolean?(true) #=> true

Why was it so designed? What advantages does varying the type in question bring in the Ruby context?

    
asked by anonymous 02.01.2018 / 23:14

1 answer

1

In a email questioning the same for Yukihiro "Matz" Matsumoto , creator of Ruby, he responds:

  
    

Is there any good reason why these [ TrueClass and FalseClass ] do not inherit Bool or something like this?

  
     

Is there any reason to inherit Bool , where true and false are only representations of true values?

My understanding of this is that a class is made to group similar objects in terms of value, semantics, and / or behavior.

As Matz said, he saw no similarity from these criteria between true and false . In fact they are even opposites.

For those who want to read more about this, there is a thread in Ruby-Forum which deals with the same issue, where Matsumoto is also ready.

  

There is nothing that true and false share, so no class Boolean . Also, in Ruby, everything behaves like a Boolean value.

    
03.01.2018 / 12:32