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: ActiveModel::Type::Boolean.new.seralize(value) in the console
Examples:
ActiveModel::Type::Boolean.new.seralize("") => nil ActiveModel::Type::Boolean.new.seralize(nil) => nil ActiveModel::Type::Boolean.new.seralize(:f) => false ActiveModel::Type::Boolean.new.seralize(false) => false ActiveModel::Type::Boolean.new.seralize("true") => true ActiveModel::Type::Boolean.new.seralize(true) => true ActiveModel::Type::Boolean.new.seralize("foobar") => true