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

end

Lets check the same in irb :

>> Boolean(true)
>> true

>> Boolean(false)
>> false

>> Boolean(‘false’)
>> false

>> Boolean(‘f’)
>> false

Advertisements

4 Comments »

  1. It’s more correct to do

    module String

    def to_boolean
    return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
    return false if self == false || self.nil? || self =~ (/(false|f|no|n|0)$/i)
    raise ArgumentError.new(“invalid value for Boolean: \”#{self}\””)
    end

    end

    Comment by Anton — November 25, 2011 @ 2:18 pm

    • Thanks Anton

      Comment by Veerasundaravel — November 25, 2011 @ 2:24 pm

  2. this could be further distilled:

    def to_boolean
    (value.to_s =~ (/(true|t|yes|y|1)$/i)) == 0
    end

    I don’t believe that monkey-patching module String would allow this method to be called on a TrueClass or FalseClass, so self == true && self == false are moot. Also- why raise an argument error?

    Comment by Kevin — October 26, 2013 @ 2:21 am

  3. You can use wannabe_bool gem.
    https://github.com/prodis/wannabe_bool

    This gem implements a `#to_b` method for String, Integer, Symbol and NilClass classes.

    Comment by Fernando Hamasaki (@Prodis) — August 28, 2015 @ 8:43 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: