Ever wonder how to convert the String values of “true” or “false” to the boolean value true false in rails? Rails, specifically ActiveRecord::ConnectionAdapters::Column has a built in function which does just this called value_to_boolean.
Example(s):
"true".value_to_boolean
params[:is_string_true_false].value_to_boolean
will return the boolean value true.
For plain old Ruby, this is not so straightforward, but simple enough. Since you can very easily override Ruby core classes, we’re going to override the Ruby String class and add a to_bool function which converts a String value to Boolean.
class String def to_bool return true if self == true || self =~ (/(true|t|yes|y|1)$/i) return false if self == false || self.empty? || self =~ (/(false|f|no|n|0)$/i) raise ArgumentError.new("invalid value for Boolean: \"#{self}\"") end end
Now we can call on this method for any string. “True”.to_bool ==> true. If you pay attention to the code, you’ll notice that “1” “yes” “y” will be converted to true, and “f”, “no”, “n”, “0”, will convert to false. This works the same for value_to_boolean in rails. This is particularly helpful when getting data from form inputs.
* Caution!: One thing to note for the to_bool implementation. “”.to_bool will return false. (that is quotes with no spaces in between).
Recent Comments