Ruby: How to convert a string to boolean


I have a value that will be one of four things: boolean true, boolean false, the string "true", or the string "false". I want to convert the string to a boolean if it is a string, otherwise leave it unmodified. In other words:

"true" should become true

"false" should become false

true should stay true

false should stay false


Answers:


def true?(obj)
  obj.to_s.downcase == "true"
end