From: mail@... Date: 2017-02-07T11:56:44+00:00 Subject: [ruby-core:79467] [CommonRuby Feature#12732] An option to pass to `Integer`, `Float`, to return `nil` instead of raise an exception Issue #12732 has been updated by Jan Lelis. Although it does not solve Aaron's use case, I would suggest to have a `Integer.try_convert`, `Float.try_convert`, `Rational.try_convert`, and `Complex.try_convert` which do not raise exceptions, but just return `nil`. To keep consistency, they would just call implicit, then explicit conversion (e.g. `to_int`, then `to_i`), instead of `Integer()`'s special parsing. It only allows strict parsing, but is much cleaner, imho. Also, it would fill some empty spots in the [core conversion table](http://idiosyncratic-ruby.com/54-try-converting.html#core-classes-conversion-table) and make Ruby's conversion logic simpler. (`.try_convert`, which currently feels more like an implementation detail, could then be embraced more). To allow `Integer()` special conversion, it would still need an `exception:` option, but also `Float()`, `Rational()`, and `Complex()` would need it (since they currently also lack this feature due to not having a `try_convert`). One idea is to give every of the uppercased Kernel methods an `exception:` option, but this does not make sense for `Array()` and just would not be needed if going for the broader `try_convert` support). To summarize my suggestion in two bullet points: - Create `Integer.try_convert`, `Float.try_convert`, `Rational.try_convert`, and `Complex.try_convert` which prefer implicit conversion (if available), then explicit conversion, but return `nil` instead of raising an exception - Give `Integer()` an `exception` option to support special integer parsing without exceptions, but do not give `Float()` one ---------------------------------------- Feature #12732: An option to pass to `Integer`, `Float`, to return `nil` instead of raise an exception https://bugs.ruby-lang.org/issues/12732#change-62897 * Author: Aaron Patterson * Status: Feedback * Priority: Normal * Assignee: Yukihiro Matsumoto * Target version: ---------------------------------------- I would like to be able to pass an option to `Integer()` and `Float()` so that they don't raise an exception, but return `nil` instead. For example: ~~~ Integer(string, exception: false) ~~~ The reason I want this function is so that I can convert strings from YAML or JSON to integers if they parse correctly, or just return strings if they can't be parsed. ---Files-------------------------------- integer-parse.pdf (29 KB) -- https://bugs.ruby-lang.org/ Unsubscribe: