Skip to content

Instantly share code, notes, and snippets.

@cseeger
Forked from romansklenar/string.rb
Created March 8, 2017 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cseeger/9fb0a076b95911171fbbc5998b6f435d to your computer and use it in GitHub Desktop.
Save cseeger/9fb0a076b95911171fbbc5998b6f435d to your computer and use it in GitHub Desktop.
Ruby string to boolean type casting
class String
def to_bool
case
when self == true || self =~ /^(true|t|yes|y|1)$/i
true
when self == false || self.blank? || self =~ /^(false|f|no|n|0)$/i
false
else
raise ArgumentError.new "invalid value for Boolean: '#{self}'"
end
end
alias :to_b :to_bool
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment