How to convert a string to Boolean in Ruby on Rails 5+

Published on 2022-01-17

Converting a string value to a boolean is easy in Rails 5+.

By looking in ActiveModel::Type::Boolean class we can see how Rails does this for us:

false, 0, “0”, “f”, “F”, “false”, “FALSE”, “off”, “OFF”, :”0”, :f, , :F, :false, :FALSE, :off, :OFF - are converted into false

empty or nil string are converted to nil

and all other values are converted to true.

You can try this for yourself by calling: in the console

Examples:"") => nil => nil => false => false"true") => true => true"foobar") => true