Issue #12455 has been updated by Tsuyoshi Sawada.


If we have a variant of methods like `Kernel#Integer`, `Kernel#Float` or usage with options so that they do not raise an error but return `nil` in case the string is not appropriate, then that should suffice. For example, if we allow these methods to take an optional second argument, that would suffice.

Method signature:

```ruby
Integer(string, raise_error = true)
```

Usage:

```ruby
Integer("123", false) # => 123
Integer("foo", false) # => nil
Integer("123") # => 123
Integer("foo") # => ArgumentError
Integer("123", true) # => 123
Integer("foo", true) # => ArgumentError
```

Robert's use case would be:

```ruby
if Integer(x, false)
```

----------------------------------------
Feature #12455: Add a way for class String to determine whether it has only numbers / digits or not
https://bugs.ruby-lang.org/issues/12455#change-59635

* Author: Robert A. Heiler
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
Hello.

Not sure if that has been suggested before. If it was and not deemed fit,
please feel free to close this issue request here.

For class String, would it be possible to find out if a given String
contains only numbers, without having to do a regex check?

    x = '123'

A regex will do of course:

    if x =~ /^\d+$/

I was wondering if we could have a method that does something similar,
that is also easier to read.

Something like:

    x = '123'
    x.only_numbers?

or

    x.only_digits?

Something like that. 

I do not know whether the word "only" is good or not. Perhaps ".all_numbers?"
or ".all_digits?" would be better. But the name is secondary probably, more
important would be whether such a method would make sense for class String.

I am more interested in a method that will help avoid the use of a regex here.

The method should return true if the string has only numbers, and false
otherwise.

Anyway, thanks for reading!



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