Palak Chaudhary Palak Chaudhary - 2 months ago 10
Ruby Question

Check if a string contains only digits in ruby

I have a string which is passed as a parameter to a function. Here, I want to check if the string contains only numbers. So I had a check like below:

def check_string(string)
result = false
if string.to_i.to_s.eql? string
result = true
end
result
end


But the problem arises when a string starts with 0. In that case, a false is returned.

check_string('123') #=> true
check_string('0123') #=> false


How can I solve this issue?

Answer

You can try the following

def check_string(string)
  string.scan(/\D/).empty?
end

It would be truthy if string contains only digits.