String "true" and "false" to boolean String "true" and "false" to boolean ruby-on-rails ruby-on-rails

String "true" and "false" to boolean


As far as i know there is no built in way of casting strings to booleans,but if your strings only consist of 'true' and 'false' you could shorten your method to the following:

def to_boolean(str)  str == 'true'end


ActiveRecord provides a clean way of doing this.

def is_true?(string)  ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(string)end

ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES has all of the obvious representations of True values as strings.


Security Notice

Note that this answer in its bare form is only appropriate for the other use case listed below rather than the one in the question. While mostly fixed, there have been numerous YAML related security vulnerabilities which were caused by loading user input as YAML.


A trick I use for converting strings to bools is YAML.load, e.g.:

YAML.load(var) # -> true/false if it's one of the below

YAML bool accepts quite a lot of truthy/falsy strings:

y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF

Another use case

Assume that you have a piece of config code like this:

config.etc.something = ENV['ETC_SOMETHING']

And in command line:

$ export ETC_SOMETHING=false

Now since ENV vars are strings once inside code, config.etc.something's value would be the string "false" and it would incorrectly evaluate to true. But if you do like this:

config.etc.something = YAML.load(ENV['ETC_SOMETHING'])

it would be all okay. This is compatible with loading configs from .yml files as well.