0

code:

a = rand(1..100)
puts "Guess a number from 1 through 100!"
i = 0
loop do 
    i = i+1
    b = gets.chomp
        if b.is_a? String
        puts "Only numerical values"
    end
    if b == a
        puts "Good Job! You finished in #{i} attempts!"
        break
    end
    if b<a 
        puts "Too Low!"
    end
    if b>a
        puts "Too High!"
    end
    if b<0
        puts "Please input numbers above 0!"
    end

end

Error Message:

Guess a number from 1 through 100!
hi
Only numerical values
hi-lo.rb:14:in `<': comparison of String with 38 failed (ArgumentError)
from hi-lo.rb:14:in `block in <main>'
from hi-lo.rb:4:in `loop'
from hi-lo.rb:4:in `<main>'

My problem: basically, i want to make it so that ruby will detect when someone inputs a string instead of an integer. Thus resulting in outputting a message that states that you have entered an illegal character. It detects i am entering a string, but it shuts down the code instead of continuing the loop. Any advice? Thanks.

6
  • Side note, this is only displaying the message because i used gets.chomp instead of gets.chomp.to_i Commented Jun 28, 2017 at 12:39
  • Using gets.chomp results in stopping any if statement. Commented Jun 28, 2017 at 12:40
  • 1
    Use next to go to next item of the loop, or break to exit. Commented Jun 28, 2017 at 12:41
  • 1
    BTW gets.chomp will always be String. Commented Jun 28, 2017 at 12:42
  • And gets.chomp.to_i will always be an integer. Something more complicated is needed here (as in the linked answer, for example) Commented Jun 28, 2017 at 12:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.