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
Add your response
Add your response
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
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#