Skip to content

Instantly share code, notes, and snippets.

@yangxing-star
Created March 27, 2014 08:43
Show Gist options
  • Save yangxing-star/9803100 to your computer and use it in GitHub Desktop.
Save yangxing-star/9803100 to your computer and use it in GitHub Desktop.
"false" => false
String to Boolean in Ruby
When parsing data you may end up with string representations of various data types. For example, Boolean value might be represented as "true", "t", "yes", "y" or "1".
In order to resolve that problem with Ruby I chosed to do a quick hack. The following code adds new behaviour to String class. Such approach is called Monkey Patching. It should be used with caution as it can result in hard to track down errors.
class String
def to_bool
return true if self =~ (/^(true|t|yes|y|1)$/i)
return false if self.empty? || self =~ (/^(false|f|no|n|0)$/i)
raise ArgumentError.new "invalid value: #{self}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment