Created — forked from erskingardner/string_ext.rb

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Ruby: Convert String to Boolean

View string_ext.rb
1 2 3 4 5 6 7
class String
def to_bool
return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i)
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
end
end

I have just made the wannabe_bool gem to convert strings, integers, symbols and nil values to boolean, using a #to_b method.
https://github.com/prodis/wannabe_bool

'true'.to_b # => true
1.to_b      # => true
:true.to_b  # => true

'false'.to_b # => false
0.to_b       # => false
:false.to_b  # => false
nil.to_b     # => false

# and more
  module StringExtension
    extend ActiveSupport::Concern
    def to_bool
      result = false
      result = (!self.nil? && !(self.downcase.squish == 'false') && (self.downcase.squish == 'true' || self != '0' || self == '1'))

      result
    end
  end

so after defining my module, I just include it. And I don't want that to effect system wide.

 String.class_eval do
    include StringExtension
  end

Examples:

[13] pry(#<ProductFinder>)> >> "1".to_bool 
=> true
[14] pry(#<ProductFinder>)> 
[15] pry(#<ProductFinder>)> >> "0".to_bool 
=> false
[16] pry(#<ProductFinder>)> 
[17] pry(#<ProductFinder>)> >> "sdfj".to_bool 
=> true
[18] pry(#<ProductFinder>)> 
[19] pry(#<ProductFinder>)> >> "true".to_bool 
=> true
[20] pry(#<ProductFinder>)> 
[21] pry(#<ProductFinder>)> >> "false".to_bool
=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.