Created
March 27, 2014 08:43
-
-
Save yangxing-star/9803100 to your computer and use it in GitHub Desktop.
"false" => false
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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