S
S
Stergy2018-09-28 22:42:18
ruby
Stergy, 2018-09-28 22:42:18

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

3 answer(s)
O
oh_shi, 2018-09-28
@Stergy

Check that all characters in a string are numbers:

number = gets
if number[/^\d+$/]
или
if numbers.scan(/\D/).empty?

This must be done before numbers.to_iandguesses += 1

T
TyzhSysAdmin, 2018-09-29
@POS_troi

oh_shi don't like regular games :)

class String
    def numeric?
      Float(self) != nil rescue false
    end
end

puts "566".numeric?

"566" => true
"56.6" => true
"Hello" => false
"999Hello999" => false

A
AVKor, 2018-09-28
@AVKor

Here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question