6

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.

2
  • 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+$/ Commented Sep 17, 2013 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. Commented Jun 24, 2023 at 2:06

4 Answers 4

22

Use Integer("123") rescue nil.

Sign up to request clarification or add additional context in comments.

1 Comment

best answer in my opinion. simple. i don't know why people prefer using complex regex...
20

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

3 Comments

Nice, but what about negative numbers?
@AmitKumarGupta Not part of the OP's corpus. Simple questions get simple answers.
There might not be a negative number in the examples, but the headline question asks about integers, not whole numbers (or unsigned integers).
2

You can use regex

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

It will also check for decimals.

1 Comment

Nice, but why the \.? The question is about integers, not decimal numbers.
1
"1234223".tap{|s| break s.empty? || s =~ /\D/}.!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.