Q:

Accept only numeric input

I want to force user to enter only numeric value from console. Below is my piece of code that is supposed to do that.
puts "Enter numeric value: "
result = gets.chomp

if result.to_i.is_a? Numeric
  puts "Valid input"
else
  puts "Invalid input."
end

It prints Valid input even if I enter a string value. And the reason is that every string has some equivalent numeric value in Ruby. Can someone help me fix the condition properly so that when user enters a non-numeric value, the script prompts Invalid input.?

A:

to_i will convert any string to an integer, even if it shouldn't:
"asdf".to_i

which returns 0.
What you want to do is:
puts "Enter numeric value: "
result = gets.chomp

begin
  result = Integer(result)
  puts "Valid input"
rescue ArgumentError, TypeError
  puts "Invalid input."    
  # handle error, maybe call `exit`? 
end

Integer(some_nonnumeric_string) throws an exception if the string cannot be converted to an integer, whereas String#to_i gives 0 in those cases, which is why result.to_i.is_a? Numeric is always true.

A:

Try regular expressions, like this:
puts "Enter numeric value: "
result = gets

if result =~ /^-?[0-9]+$/
    puts "Valid input"
else
    puts "Invalid input."
end

The example above allows only digits [0..9].
If you want to read not only integers, you can allow a dot as well: ^-?[0-9]+$/. Read more about regexp in Ruby: http://ruby-doc.org/core-2.2.0/Regexp.html

