Skip to content

Instantly share code, notes, and snippets.

@ChuckJHardySnippets
Forked from erskingardner/string_ext.rb
Created March 8, 2012 11:40
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save ChuckJHardySnippets/2000623 to your computer and use it in GitHub Desktop.
Save ChuckJHardySnippets/2000623 to your computer and use it in GitHub Desktop.
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
@niltonvasques
Copy link

My approach to avoid affect whole system:

# This module add refinements to cast string to boolean
module StringToBooleanRefinements
    refine String do
      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
end

Class that will uses this refinement

class RefinedStringClass
  using StringToBooleanRefinements

   def string_true
       'true'.to_bool   
   end
   def string_false
      'false'.to_bool
   end
end

@perlun
Copy link

perlun commented Jan 27, 2017

(For reference, Ruby refinements was introduced in Ruby 2.0. So if you are stuck on some antique version, it will not work.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment