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

Published on 17-01-2022

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

← Previous post Blog index Next post →

Ready to get started? Use Callcounter API analytics to innovate faster