Last Updated: February 25, 2016
· flynfish

Ruby String to Boolean

Extend the String class to include a to_bool method:

class String
  def to_bool
    return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
    return false if self == false || self.empty? || self =~ (/(false|f|no|n|0)$/i)
    raise"invalid value for Boolean: \"#{self}\"")

If you are using rails and want empty strings to return false, then change self.empty? to self.blank?

Also you are using rails, drop this in a file located in config/initializers.

Thanks to Jeff Gardner for this!