Palak Chaudhary Palak Chaudhary - 11 months ago 64
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

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 Source

You can try the following

def check_string(string)

It would be truthy if string contains only digits.