0

Here's part of my code, the first part of the ˚ statement works, but I would like a separate message to appear for a non-numerical input such as "$boo", "ten", "idk").

puts "Candy Sold: "
candy_sold = gets.chomp.to_i
 until candy_sold >= 0 
  if candy_sold < 0
    puts "Please enter a positive number:"
    candy_sold = gets.chomp.to_i
  elsif candy_sold.class == String      # This is where the issue is
    puts "Please enter a positive number:"
    candy_sold = gets.chomp.to_i
  end
 end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Newbie
  • 15
  • 2
  • 3
    Anything you read from the terminal with `gets` is a string. Then applying `.to_i` will just return a 0 if it doesn't start with a number or translate the number. So `candy_sold.class == String` will always be false. If you want to check for numeric input, read the string (`gets.chomp`) then do something, for example, like is described here: [How to check if a variable is a number or a string](https://stackoverflow.com/questions/8616360/how-to-check-if-a-variable-is-a-number-or-a-string) (lots of different ways to do it). – lurker Apr 23 '20 at 23:18

2 Answers2

0

If you check already converted number there is no way to tell if it was initially valid format or not. You have to compare with initial input somehow.

One of the solutions:

ask_for_amount = true

while ask_for_amount
  candy_number_input = gets.chomp.strip
  candy_sold = candy_number_input.to_i

  if candy_number_input != candy_sold.to_s
    puts "Please enter a valid positive number:"
  elsif candy_sold < 0
    puts "Please enter a positive number:"
  else
    ask_for_amount = false
  end
end

Olkin
  • 181
  • 1
  • 5
0

If I am understanding your question correct, you just want to allow only positive numbers. In this case, you can use the cover? method with a range.

puts "Candy Sold: "
candy_sold = gets.chomp
until ('0'..'9').cover? candy_sold
  puts "Please enter a positive number"
  candy_sold = gets.chomp
end

Candy Sold: 
> Hello
=> Please enter a positive number
> -97
=> Please enter a positive number
> -0
=> Please enter a positive number
> 1
=> nil
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sri
  • 2,233
  • 4
  • 31
  • 55
  • You're amazing! Thank you, I've been trying to solve this for a few days now and this worked perfectly! – Newbie Apr 24 '20 at 01:26