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 =
If you mean integer by "numeral", then:
puts "Enter numeric value: "
result = gets.chomp
case result
when /\D/, ""
puts "Invalid input"
else
puts "Valid input."
end
It also takes care of empty strings, which would be turned into 0
by to_i
, which you probably do not want.
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
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.