Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Ruby: Convert String to Boolean
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
@prodis

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
@rubyrider
  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
@pacharanero

blank? throws a NoMethodError in Ruby 2.2.1, I think because blank? is now replaced with empty?

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.