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.
– Maniero
I don’t need it on account of Duck Typing, huh? @Maniero
– vinibrsl
You don’t need it 'cause you can use it
true
andfalse
as any language (https://docs.ruby-lang.org/en/2.2.0/keywords_rdoc.html)– Maniero
The problem is not even the type validation, it was an example I tried to give to contextualize. I came across
TrueClass
andFalseClass
and I questioned that choice. @Maniero– vinibrsl