Check if a string contains only digits in ruby

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.


def check_string(str)
  str !~ /\D/
end

check_string '123'
  #=> true
check_string ''
  #=> true
check_string '1a2'
  #=> false

A number can be negative, or a float. So if these are allowed, consider this solution:

def is_numberic?(str)
    str == "#{str.to_f}" || str == "#{str.to_i}"
end

some input which evaluate to true

pry(main)> is_numberic? '5'
=> true
pry(main)> is_numberic? '58127721'
=> true
pry(main)> is_numberic? '58127721.737673'
=> true
pry(main)> is_numberic? '0'
=> true
pry(main)> is_numberic? '1818'
=> true
pry(main)> is_numberic? '0.1'
=> true
pry(main)> is_numberic? '0.0'
=> true
pry(main)> is_numberic? '11.29'
=> true
pry(main)> is_numberic? '-0.12'
=> true
pry(main)> is_numberic? '-29'
=> true

the input which evaluate to false

pry(main)> is_numberic? '10 years'
=> false
pry(main)> is_numberic? '01'
=> false
pry(main)> is_numberic? '00'
=> false
pry(main)> is_numberic? '0.10'
=> false
pry(main)> is_numberic? ''
=> false

As you can see, there're several cases which probably should be supported, eg '0.10', but are not. In this case, the permitted input is '0.1'.

Tags:

Ruby