Check if string contains only positive numbers in Ruby

ruby, string

Solution

Of course `Regexp` is good for this:

string = "123abcd"
/^(?<num>\d+)$/ =~ string
num # => nil

string = "123"
/^(?<num>\d+)$/ =~ string
num # => '123' # String

So if you need to check the condition:

if /^(?<num>\d+)$/ =~ string
   num.to_i # => 123
   # do something...
end

`#to_i` method of `String` isn't valid for your case because it will return a number, if string is even with letters:

string = "123abcd"
string.to_i # 123

Problem

I am really new to ruby and want know if it's possible to check if a string contains only positive numbers using regex or some other function? ``` str = "123abcd" #return false because it contains alphabets str = "153" #return true because of all numbers ```

Original source