Ruby: How to convert a string to boolean

emery picture emery · Mar 25, 2016 · Viewed 135.9k times · Source

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

Answer

steenslag picture steenslag · Mar 25, 2016
def true?(obj)
  obj.to_s.downcase == "true"
end