I have a string "1234223"
and I want to check whether the value is an integer/number.
How can I do that in one line?
I have tried
1 =~ /^\d+$/
=> nil
"1a" =~ /^\d+$/
=> nil
Both line are returning nil.
I have a string "1234223"
and I want to check whether the value is an integer/number.
How can I do that in one line?
I have tried
1 =~ /^\d+$/
=> nil
"1a" =~ /^\d+$/
=> nil
Both line are returning nil.
Use Integer("123") rescue nil
.
If you're attempting to keep similar semantics to the original post, use either of the following:
"1234223" =~ /\A\d+\z/ ? true : false
#=> true
!!("1234223" =~ /\A\d+\z/)
#=> true
A more idiomatic construction using Ruby 2.4's new Regexp#match? method to return a Boolean result will also do the same thing, while also looking a bit cleaner too. For example:
"1234223".match? /\A\d+\z/
#=> true
You can use regex
"123".match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
It will also check for decimals
.