ActiveSupport could add a boolean conversion method to String and Fixnum

Hey all, this is something that’s come up again and again with various projects, and typecasting values from params as booleans. This could be represented as a to_bool method added to the String class. Also, possibly to Fixnum, and I’ll explain why later.

I’m thinking the following values could be true:

“1”, “true”, “t”, “y”, “yes” (of course, case insensitive)

And the following values could be false:

“0”, “false”, “f”, “n”, “no” (again, case insensitive)

The reasoning for also including on Fixnum is to convert the 1/0 to true/false whether or not it’s a string.

Any thoughts on this? I couldn’t find any notes or discussions in this forum or in the repo about this. I have a branch ready to go, curious what the community thinks.

Interesting idea just not sure if the string class would ever be responsible for converting itself to another type. Interested in other people’s thoughts on this.

Hey!

I think this would cause confusion. First, the logical values of `string` and `string.to_bool` would be different. Second, what would you return for a string "foobar"?

Best regards

Conversion between types is fairly common in Ruby. With that said I’d recommend you look into ActiveModel::Type::Boolean.new.cast(my_value), which handles the all cases above.

String already converts itself to other types. “4”.to_i becomes the Integer 4. Invalid values, other than the ones listed (like “foobar”) would raise an argument error.

Wael, thanks for the reference to ActiveModel! This is definitely similar. Would this implementation be better for everyone? I would like to be explicit about true/false values, whereas the implementation in ActiveModel only has explicit false types. I feel this belongs on ActiveSupport because it’s commonly included on other projects (including ActiveModel), and has no further dependencies.

Yes, actually Rails did have a TRUTHY_VALUES collection, similar to the false collection now, but I don’t remember why they deprecated it. Maybe looking into that might address some of your issues.

I searched the git history and couldn’t find anything. Do you have any other details?

My specific need has arisen not from ActiveRecord or a model, but transmitting data through to an API. Occasionally, the way we ask a question requires an inversed update to the API. i.e. the user answers “Yes” and we need to submit false to the API. We’ve been proactive about testing value equality, but I thought this would be an easier implementation and might be useful to the community.

I found this commit: https://github.com/rails/rails/commit/e01a46f1f0e21d9018906a6a8dcfdae2d92f32ae

Another thing worth considering is I18n, so "yes" or "oui", that kinda thing.

Thanks for that, and all the info!