4

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vijay Chouhan
  • 4,613
  • 5
  • 29
  • 35
  • 1
    For me your solution works fine, it is just that in the first case you are running the regexp on an int and not a string. Try to change the first line to "1" =~ /^\d+$/ – hirolau Sep 17 '13 at 14:58
  • Do you want _any_ integer, or an integer that is within the range of a built-in numeric type? If the former use regex, if the later use type conversion with `rescue`. – Martin Kealey Jun 24 '23 at 02:06

4 Answers4

20

Use Integer("123") rescue nil.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Victor Moroz
  • 9,167
  • 1
  • 19
  • 23
19

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
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
2

You can use regex

"123".match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true

It will also check for decimals.

Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38
1
"1234223".tap{|s| break s.empty? || s =~ /\D/}.!
sawa
  • 165,429
  • 45
  • 277
  • 381