Answer the question
In order to leave comments, you need to log in
How to check if a value is a number in Ruby?
I'm learning the basics of ruby. I wrote a simple application in which you need to guess the hidden number. How to implement the check function in this code, if not a number is entered, so that the program would display an alert and ask to re-enter the number, and without counting the erroneous input as an attempt.
puts 'Welcome to "Get my number!"'
print 'What is your name? '
name = gets.chomp
puts "Welcome to our game #{name}!"
sleep 1
rand_number = rand(100) + 1
guesses = 0
guessed_it = false
print "You need to guess a number from 0 to 100! \n"
sleep 1
until guesses == 10 || guessed_it == true
puts "You`ve got #{10 - guesses} guesses left!"
print "Make a guess: "
number = gets.to_i
if number > rand_number
puts ""
puts "Oops. Your guess was HIGH"
elsif number < rand_number
puts ""
puts "Oops. Your guess was LOW"
elsif number == rand_number
puts ""
puts "Good job #{name}!"
puts "You guessed my number in #{guesses} guesses!"
guessed_it = true
end
guesses += 1
end
unless guessed_it
puts "Sorry. You didn't get my number. (It was #{rand_number})"
end
Answer the question
In order to leave comments, you need to log in
Check that all characters in a string are numbers:
number = gets
if number[/^\d+$/]
или
if numbers.scan(/\D/).empty?
numbers.to_i
andguesses += 1
oh_shi don't like regular games :)
class String
def numeric?
Float(self) != nil rescue false
end
end
puts "566".numeric?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question