Veerasundaravel's Ruby on Rails Weblog

October 26, 2010

String to Boolean conversion in Ruby

Filed under: Ruby — Tags: , , , , , , — Veerasundaravel @ 11:33 pm

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“invalid value for Boolean: \”#{string}\””)


Lets check the same in irb :

>> Boolean(true)
>> true

>> Boolean(false)
>> false

>> Boolean(‘false’)
>> false

>> Boolean(‘f’)
>> false

%d bloggers like this: