Feature #8536

Implement is_numeric? family of methods

Added by wardrop (Tom Wardrop) over 4 years ago. Updated about 4 years ago.

Target version:


I think Ruby is in dire need of a convenient method for determining whether a string can be safely converted to a number. It's a trivial problem, but with no trivial solution. The most common methods include using regex, or trying to convert the value to the desired type, rescuring any exceptions that are raised. These are not desirable by any means.

I propose a number of new methods be added, either to each of the number classes such as (({Integer.is_integer?})) and (({Numeric.is_numeric?})), to a single parent such as Numeric. For convenience, corresponding methods may also be added to the String class. The methods I propose are...

  • is_numeric?
  • is_integer?
  • is_float?
  • is_rationale?

With the exception of numeric, if each of the other methods return true, that value should be safe to use with the corresponding (({Integer("5")})) style methods, and (({to_i})) methods. These boolean methods should behave like the (({Integer("5")})), in that they should disregard/strip whitespace for example.

I think it'd make a nice feature enhancement to Ruby 2.1.


#1 [ruby-core:56287] Updated by phluid61 (Matthew Kerwin) about 4 years ago

I am +1, if you change (({is_rationale?})) to (({is_rational?}))

Implementation question: is it reasonable to refactor rb_cstr_to_inum (etc.) to conditionally not perform the Integer object allocation?

#2 [ruby-core:56292] Updated by nobu (Nobuyoshi Nakada) about 4 years ago

There is no "is_"+adjective+"?" built-in methods.
And check-then-convert seems redundant.

#3 [ruby-core:57524] Updated by naruse (Yui NARUSE) about 4 years ago

  • Status changed from Open to Assigned
  • Assignee set to matz (Yukihiro Matsumoto)
  • Target version changed from 2.1.0 to next minor

Also available in: Atom PDF