How to check if users didn't put an integer in if statement in a loop. I want the if statement to check if the user didn't put an integer, the system gonna say "please put an integer" Right now, everything works fine, but when user input a decimal number, the program will convert it to an integer. I want the program to say "you need to put an integer" when user put a decimal number.
I tried if soap.match(/^[\d]+$/).nil? and other methods, but didn't work. I think I need to change some code in 'if (soap_type = SOAPS[soap.to_i])', but I don't know how to change it.
SOAPS = {
1 => 'face soap',
2 => 'bar soap',
3 => 'shave soap',
4 => 'shampoo soap'
}.freeze
loop do
puts "What type of soaps do you want? (#{SOAPS.map { |k, v| "#{k} - #{v}" }.join(', ')}) Please put a number from 1 - 4 "
soap = gets
if (soap_type = SOAPS[soap.to_i])
puts "Great! You want #{soap_type}."
break
elsif !soap.match (/\A[-+]?[0-9]*\.?[0-9]+\Z/)
puts "You didn't enter an integer, please put an integer from 1-4"
else
puts "#{soap.inspect} is not a valid integer, please try again."
end
end
I hope when the user input a decimal number, the program gonna say You didn't enter an integer, please put an integer.