Safe Bool Type - Bool(), to_b, to_bool, and More
safebool gem / library - safe bool(ean) type adds Bool(), to_b, to_bool, bool?, false?, true?, true.is_a?(Bool)==true, false.is_a?(Bool)==true, and more
- home :: github.com/s6ruby/safebool
- bugs :: github.com/s6ruby/safebool/issues
- gem :: rubygems.org/gems/safebool
- rdoc :: rubydoc.info/gems/safebool
Why Bool in Ruby?
false.class #=> FalseClass
true.class #=> TrueClass
false.is_a?(Bool) #=> NameError: uninitialized constant Bool
true.is_a?(Bool) #=> NameError: uninitialized constant Bool
true.class.ancestors #=> [TrueClass, Object, Kernel, BasicObject]
false.class.ancestors #=> [FalseClass, Object, Kernel, BasicObject]
# -or-
"true".to_b #=> NoMethodError: undefined method `to_b' for String
1.to_b #=> NoMethodError: undefined method `to_b' for Integer
Bool("true") #=> NoMethodError: undefined method `Bool' for Kernel
Bool(1) #=> NoMethodError: undefined method `Bool' for Kernel
...
Why? Why not? Discuss.
Usage
false.is_a?(Bool) #=> true
true.is_a?(Bool) #=> true
true.class.ancestors #=> [TrueClass, Bool, Object, Kernel, BasicObject]
false.class.ancestors #=> [FalseClass, Bool, Object, Kernel, BasicObject]
# -or-
"true".to_b #=> true
1.to_b #=> true
Bool("true") #=> true
Bool(1) #=> true
"false".to_b #=> false
0.to_b #=> false
Bool("false") #=> false
Bool(0) #=> false
How about handling errors on invalid bool values when converting / parsing?
to_balways return a bool even if the conversion / parsing failed e.g.true(for numbers) andfalse(for strings) on errorparse_bool/to_boolalways returnsnilif the conversion / parsing failedBool()always raises aTypeErrorif the conversion / parsing failed
"2".to_b #=> false
"2".to_bool #=> nil
2.to_b #=> true
2.to_bool #=> nil
Bool("2") #=> TypeError: cannot convert "2":String to Bool; method parse_bool/to_bool expected
Bool(2) #=> TypeError: cannot convert 2:Fixnum to Bool; method parse_bool/to_bool expected
...
More methods added to Kernel include bool?, false?, true?.
Example:
# bool? - returns true if object class is TrueClass or FalseClass, otherwise false
true.bool? #=> true
false.bool? #=> true
nil.bool? #=> false
# false? - returns true if object class is FalseClass, otherwise false
false.false? #=> true
true.false? #=> false
nil.false? #=> false
# true? - returns true if object class is TrueClass, otherwise false
true.true? #=> true
false.true? #=> false
nil.true? #=> false
And some more.
See the safebool.rb source.
License

The safebool scripts are dedicated to the public domain.
Use it as you please with no restrictions whatsoever.
Questions? Comments?
Send them along to the wwwmake forum. Thanks!