I was working in a file processing task, I expected to test an input as Boolean or not. But my input can as ‘false’ or false or 0.
Then I searched for Ruby built-in conversion method, but no success. So I build a custom method to convert the string representation into a Boolean object. Lets build a kernel module with Boolean method.
module Kernel
def Boolean(string)
return true if string== true || string =~ (/(true|t|yes|y|1)$/i)
return false if string== false || string.nil? || string =~ (/(false|f|no|n|0)$/i)
raise ArgumentError.new(“invalid value for Boolean: \”#{string}\””)
endend
Lets check the same in irb :
>> Boolean(true)
>> true>> Boolean(false)
>> false>> Boolean(‘false’)
>> false>> Boolean(‘f’)
>> false