Feature #12455
openAdd a way for class String to determine whether it has only numbers / digits or not
Description
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!
Updated by sawa (Tsuyoshi Sawada) over 8 years ago
I am interpreting that this proposal is actually interested in integers with signatures (+/-) as well, not just digits.
If we have variants 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:
Integer(string, raise_error = true)
Usage:
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:
if Integer(x, false)
Updated by shyouhei (Shyouhei Urabe) over 8 years ago
We looked at this issue at yesterday's developer meeting.
- For the proposed functionality: why do you want to detect numbers? Because it would make more sense to convert it to integer, not just detection.
- For Integer() extension: there is no constructor method that takes arguments like this.
Updated by nobu (Nobuyoshi Nakada) over 8 years ago
I feel that to_i
extension might be better than Integer
.
"foo".to_i #=> 0
"foo".to_i(fallback: nil) #=> nil