Take me home

Simple human input boolean parser

Written by August Lilleaas, published November 24, 2007

Parsing human input – “yes”, “no”, “t” and so on – and converts it to a boolean, with a simple interface.

Converts human input to a boolean. Used this in a keyword search thingie of mine, whene users could go published:true, published:yes, published:0 and so on, and have the booleans parsed properly.

TRUE_VALUES = %w( yes y true t 1 )
FALSE_VALUES = %w( no n false f 0 )

class String
  def to_boolean
    case self.downcase.strip
    when *TRUE_VALUES
      true
    when *FALSE_VALUES
      false
    end
  end
end

Adapt the constants to your needs. Any unmatched value would simply return nil.

"yes".to_boolean
# => true

"no".to_boolean
# => false

"1".to_boolean
# => true

"kitten".to_boolean
# => nil

Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.