patternrubyMinor
Choosing a magic number between 0 and 9
Viewed 0 times
numbermagicbetweenandchoosing
Problem
I wrote a little script that asks the user to choose a number between the 0 and 9. Wile he/she is entering a choice, the program tells him/her if the number is too high and too low.
Nothing fancy, just a couple of
Nothing fancy, just a couple of
while and ifs. It's very ugly and has imperative code with mixed responsibilities. I was wondering if there are some Ruby idioms that would make this code more readable and compact. I'm looking for some functions like in functional languages, or maybe there are special Ruby functions I'm not aware off. I don't want to define functions and classes for this simple program.keepGoing = true
numberToGuess = rand(10)
firstRun = true
response = ''
while keepGoing
if firstRun
puts 'Find the magic number between O and 9'
firstRun = false
end
proposedN = gets.chomp.to_i
if proposedN == numberToGuess
firstRun = true
puts "You found the correct number : #{numberToGuess}"
puts 'Another try ? (Y/N)'
numberToGuess = rand(10)
response = gets.chomp
while response != 'N' and response != 'Y'
puts 'Please fill in either Y or N'
response = gets.chomp
end
response == 'N' ? keepGoing = false : keepGoing = true
response = ''
else
if proposedN > numberToGuess
puts 'Too high'
else
puts 'Too low'
end
end
endSolution
Well, you already identified the main issue with your code, and I concur: the imperative style. Also, note that this code should have two loops and you are doing it all in one, that's why you have to use flags all over the place. Since you asked for a functional solution, no
If you want to validate the input, create a method
while nor loop, use recursion:def guess_number(number_to_guess)
guess = gets.to_i
if guess == number_to_guess
puts("You found the correct number: #{number_to_guess}")
else
puts(guess > number_to_guess ? "Too high" : "Too low")
guess_number(number_to_guess)
end
end
def game
puts('Find the magic number between O and 9')
guess_number(rand(10))
print('Another try? (Y/N): ')
if gets.strip.downcase == "y"
game
end
end
gameIf you want to validate the input, create a method
def get(validation_regexp) and use it: get(/^\d+$/) and get(/^[yYnN]$/).Code Snippets
def guess_number(number_to_guess)
guess = gets.to_i
if guess == number_to_guess
puts("You found the correct number: #{number_to_guess}")
else
puts(guess > number_to_guess ? "Too high" : "Too low")
guess_number(number_to_guess)
end
end
def game
puts('Find the magic number between O and 9')
guess_number(rand(10))
print('Another try? (Y/N): ')
if gets.strip.downcase == "y"
game
end
end
gameContext
StackExchange Code Review Q#98077, answer score: 2
Revisions (0)
No revisions yet.