Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains only digits in ruby

Tags:

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?

like image 690
Palak Chaudhary Avatar asked Sep 28 '16 09:09

Palak Chaudhary


People also ask

How do you get an integer from a string in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.

How do I find a string in Ruby?

Syntax: str. include? Parameters: Here, str is the given string. Returns: true if the given string contains the given string or character otherwise false.


1 Answers

You can try the following

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

It would be truthy if string contains only digits or if it is an empty string. Otherwise returns false.

like image 86
Aleksey Avatar answered Sep 18 '22 14:09

Aleksey