Take me home

Simple human input boolean parser

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
    when *FALSE_VALUES

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

# => true

# => false

# => true

# => nil

Questions or comments?

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