Why don’t booleans have a common class in Ruby?

Asked

Viewed 111 times

2

Ruby doesn’t have a class Boolean. I realized that boolean objects are of specific classes depending on the value, see:

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

Different from other languages, such as C# and Java, where true and false are of the type bool, in 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 how the only way to see if an object is of a Boolean type. Otherwise, it would be to 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 designed like this? What advantages does the type of value in question bring in the Ruby context?

  • Do you have any context? Why don’t you have to do this.

  • I don’t need it on account of Duck Typing, huh? @Maniero

  • 1

    You don’t need it 'cause you can use it true and false as any language (https://docs.ruby-lang.org/en/2.2.0/keywords_rdoc.html)

  • The problem is not even the type validation, it was an example I tried to give to contextualize. I came across TrueClass and FalseClass and I questioned that choice. @Maniero

1 answer

1


In a e-mail questioning the same to Yukihiro "Matz" Matsumoto, creator of Ruby, he replies:

Any good reason why these [TrueClass and FalseClass] do not inherit Bool or something like?

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 matters of value, semantics and/or behavior.

In what 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 on this subject, there is a thread at Ruby-Forum that deals with the same issue, where Matsumoto also prepares.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.