Skip to content

Instantly share code, notes, and snippets.

@AWaselnuk
Last active August 29, 2015 14:00
Show Gist options
  • Save AWaselnuk/11409255 to your computer and use it in GitHub Desktop.
Save AWaselnuk/11409255 to your computer and use it in GitHub Desktop.
Boolean typecasting.
# from http://drawingablank.me/blog/ruby-boolean-typecasting.html
class Fixnum
def to_bool
return true if self == 1
return false if self == 0
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
end
end
# from http://drawingablank.me/blog/ruby-boolean-typecasting.html
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment