Skip to content

Instantly share code, notes, and snippets.

@timothee-alby
Forked from equivalent/README.md
Last active August 29, 2015 14:08
Show Gist options
  • Save timothee-alby/6fe2a92af16bd030c730 to your computer and use it in GitHub Desktop.
Save timothee-alby/6fe2a92af16bd030c730 to your computer and use it in GitHub Desktop.
Easily any type to boolean in Ruby
module StringToBoolean
def to_bool
return true if self == true || self.strip =~ (/\A(true|t|yes|y|1)\Z/i)
false
end
end
class String; include StringToBoolean; end
module BooleanToBoolean
def to_bool;return self; end
end
class TrueClass; include BooleanToBoolean; end
class FalseClass; include BooleanToBoolean; end
module NilToBoolean
def to_bool
false
end
end
class NilClass; include NilToBoolean; end
module NumberoBoolean
def to_bool
return false if self == 0
true
end
end
class Integer; include NumberoBoolean; end
class Fixnum; include NumberoBoolean; end
class Bignum; include NumberoBoolean; end
class Float; include NumberoBoolean; end
class Rational; include NumberoBoolean; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment