Conversion to boolean in Ruby
As you probably know, ruby doesn't have Boolean
class, true
and false
are instances of their own classes TrueClass
and FalseClass
. Kernel
module adds several methods for conversion between primitive types such as Array()
, Integer()
, Float()
etc. to global space however Boolean()
is lacking. Lets make it!
module Conversions
module_function
def Boolean(value)
case value
when true, 'true', 1, '1', 't' then true
when false, 'false', nil, '', 0, '0', 'f' then false
else
raise ArgumentError, "invalid value for Boolean(): \"#{value.inspect}\""
end
end
end
Edit: As suggested by @dacoxall in commetns, Boolean()
is now raising exceptions for not meaningful values.
Desired usage:
# 1. because of module_function, you can call it directly
puts Conversions.Boolean("true").class
# => TrueClass
# 2. or include module to your class or to the global space (as Kernel module does with Integer(), String(), etc.)
include Conversions
puts Boolean("true").class
# => TrueClass
Here is a gist with alternative implementations and benchmarks.
Do you have a better Boolean conversion implementation? Share it!
Written by Vojtěch Kusý
Related protips
2 Responses
It is probably better to raise an exception if the value isn't obviously convertible. Like how Integer("a") isn't valid. Boolean("what") makes little sense IMO
@dacoxall Yeah, it makes sense for general use, I'll update the example to include the false values and raise TypeError if value is not found. If someone want to make Boolean("what") false he can always do it in the rescue block. Thanks!