Issue #12968 has been updated by Nobuyoshi Nakada.


Only "invalid value for Integer()" from a string?
`Integer` can raise exceptions other than  `ArgumentError` against a string, for example.

```ruby
Integer(nil)           #=> can't convert nil into Integer (TypeError)
Integer(Object.new)    #=> can't convert Object into Integer (TypeError)
Integer(Object.new, 2) #=> base specified for non string value (ArgumentError)
Integer("", 1)         #=> invalid radix 1 (ArgumentError)
X=Struct.new(:to_i)
Integer(X.new("a"))    #=> can't convert #X to Integer (X#to_i gives String) (TypeError)
```

----------------------------------------
Feature #12968: Allow default value via block for Integer(), Float() and Rational()
https://bugs.ruby-lang.org/issues/12968#change-61635

* Author: Stefan Schler
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
`Kernel` provides the global conversion functions `Integer()`, `Float()` and `Rational()`. Each one convert its argument to the respective type.

Parsing errors are signaled by raising a `TypeError` or an `ArgumentError`.

I often use these methods to parse numeric string values, but I find the need for a `rescue ArgumentError` block quite annoying an distracting.

I therefore request a new feature: `Integer()`, `Float()` and `Rational()` should take an _optional block_ that serves as a callback when parsing failed.

Examples:

```ruby
Integer('foo')                #=> ArgumentError  (just as before)
Integer('foo') { 0 }          #=> 0              (same as 'foo'.to_i)
Integer('foo') { nil }        #=> nil
Integer('foo') { Float::NAN } #=> NaN
```

This resembles the way `Hash#fetch` or `Hash#fetch_values` work when a block is given.

Although not used in the examples above, any arguments should be passed along to the block, i.e. `Integer('foo') { |arg, base| ... }`



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>