Project

General

Profile

Actions

Feature #12968

open

Allow default value via block for Integer(), Float() and Rational()

Added by sos4nt (Stefan Schüßler) over 7 years ago. Updated almost 7 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:78247]

Description

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:

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| ... }


Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #12732: An option to pass to `Integer`, `Float`, to return `nil` instead of raise an exceptionClosedmatz (Yukihiro Matsumoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0