calculate total number of guesses in number guessing game ruby - ruby

To calculate $totalNoOfGuesses you would add $noOfGuesses together from each game played, correct? How do I execute that in my code? I've tried several different options, but it doesn't work. Am I supposed to be creating an array or something?
def play_game
$noOfGuesses=0
$gameCount+=1
number = generate_number
loop do
print "\nEnter your guess and press the Enter key: "
reply = STDIN.gets
reply.chop!
reply = reply.to_i
$noOfGuesses+=1
Between this would be if reply > or <, too high or too low... reply = get.to_i
$noOfGuesses=0
$gameCount=0
$totalNoOfGuesses=0
$avgNoOfGuesses=0
answer = ""
loop do
Console_Screen.cls
print "Are you ready to play the Ruby Number Guessing Game? (y/n): "
answer = STDIN.gets
answer.chop!
break if answer == "y" || answer == "n"
end
if answer == "n"
Console_Screen.cls
puts "Okay, perhaps another time.\n\n"
else
loop do
SQ.play_game
Console_Screen.cls
print "It took you #{$noOfGuesses} attempt#{'s' if $noOfGuesses > 1}.\n"
print "You have played #{$gameCount} time#{'s' if $gameCount > 1}.\n"
print "It has taken you #{$totalNoOfGuesses} attempts in #{$gameCount} game#{'s' if $gameCount >1}.\n\n"

Related

How do I display the largest number in an array in Ruby? [duplicate]

This question already has answers here:
How to find a min/max with Ruby
(5 answers)
Closed 4 years ago.
I have a homework assignment that I need to finish. I think most of the code is working but I am having trouble with the last part. I need to display the largest number that a user enters (into an array). Below is the code I have so far. I am open to any suggestions. Thanks in advance.
Here's the description of the assignment:
Write a Ruby application that allows a user to input a series of 10 integers and determines and prints the largest integer. Your program should use at least the following three variables:
a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed).
b) number: The integer most recently input by the user.
c) largest: The largest number found so far.
class Screen
def cls
puts ("\n")
puts "\a"
end
def pause
STDIN.gets
end
end
class Script
def display_instructions
Console_Screen.cls
print "This script will take the user input of 10 integers and then
will
print the largest."
print "\n\nPress enter to continue."
Console_Screen.cls
Console_Screen.pause
end
def getNumber #accepts user input
list = Array.new
10.times do
Console_Screen.cls
print "This script accepts 10 integers."
print "\n\nPlease type an integer and press enter."
input = STDIN.gets
input.chop!
list.push(input)
end
end
def display_largest(number) #displays the largest integer entered by the
user
Console_Screen.cls
print "The largest integer is " +
end
def runScript
number = getNumber
Console_Screen.cls
display_largest(number)
end
end
#Main Script Logic
Console_Screen = Screen.new
LargestNum = Script.new
answer = ""
loop do
Console_Screen.cls
print "Are you ready to start the script? (y/n): "
print "\n\nWould you like instructions on how this script works? (h): "
answer = STDIN.gets
answer.chop!
break if answer =~ /y|n|h/i
end
if answer == "h" or answer == "H"
LargestNum.display_instructions
print "Are you ready to start the script? (y/n): "
answer = STDIN.gets
answer.chop!
end
if answer == "n" or answer == "N"
Console_Screen.cls
puts "Okay, maybe another time.\n\n"
Console_Screen.pause
else
loop do
LargestNum.runScript
print "\n\nEnter Q to quit or press any key to run the script again: "
runAgain = STDIN.gets
runAgain.chop!
break if runAgain =~ /Q/i
end
end
This question has been asked and answered so many times before. Personally I think, as this answer suggests, the built in .max is the best solution.
[1, 3, 5].max #=> 5
Have you learned about for loops yet? You have to iterate through the array. For a very trivial example, you can do something like
max = 0
for element in list
if element > max
max= element
return max

Ruby script crashes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have the following code that I am trying to learn from this Ruby book and it keeps crashing, I have spent hours trying to fix. If anyone has any clue why this is happening please let me know. I am not enjoying Ruby
# Define custom classes ---------------------------------------------------
#Define a class representing the console window
class Screen
def cls #Define a method that clears the display area
puts ("\n" * 25) #Scroll the screen 25 times
puts "\a" #Make a little noise to get the player's attention
end
def pause #Define a method that pauses the display area
STDIN.gets #Execute the STDIN class's gets method to pause script
#execution until the player presses the enter key
end
end
#Define a class representing the Ruby Number Guessing Game
class Game
#This method displays the game's opening screen
def display_greeting
Console_Screen.cls #Clear the display area
#Display welcome message
print "\t\t Welcome to the Ruby Number Guessing Game!" +
"\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
"continue."
Console_Screen.pause #Pause the game
end
#Define a method to be used to present game instructions
def display_instructions
Console_Screen.cls #Clear the display area
puts "INSTRUCTIONS:\n\n" #Display a heading
#Display the game's instructions
puts "This game randomly generates a number from 1 to 100 and"
puts "challenges you to identify it in as few guesses as possible."
puts "After each guess, the game will analyze your input and provide"
puts "you with feedback. You may take as many turns as you need in"
puts "order to guess the game's secret number.\n\n"
puts "Game will stop if you have guessed 10 times.\n\n\n"
puts "Good luck!\n\n\n\n\n\n\n\n\n"
print "Press Enter to continue."
Console_Screen.pause #Pause the game
end
#Define a method that generates the game's secret number
def generate_number
#Generate and return a random number between 1 and 100
return randomNo = 1 + rand(1000)
end
#Define a method to be used control game play
def play_game
#Call on the generate_number method in order to get a random number
number = generate_number
#Loop until the player inputs a valid answer
loop do
Console_Screen.cls #Clear the display area
if answer == "c"
print "Game count : #{$gameCount}"
end
#Prompt the player to make a guess
print "\nEnter your guess and press the Enter key: "
reply = STDIN.gets #Collect the player's answer
reply.chop! #Remove the end of line character
reply = reply.to_i #Convert the player's guess to an integer
#Validate the player's input only allowing guesses between 1 and 100
if reply < 1 or reply > 1000 then
redo #Redo the current iteration of the loop
end
#Analyze the player's guess to determine if it is correct
if reply == number then #The player's guess was correct
Console_Screen.cls #Clear the display area
print "You have guessed the number! Press enter to continue."
Console_Screen.pause #Pause the game
break #Exit loop
elsif reply < number then #The player's guess was too low
Console_Screen.cls #Clear the display area
print "Your guess is too low! ( valid range: 1 - 1000) Press Enter to continue."
Console_Screen.pause #Pause the game
elsif reply > number then #The player's guess was too high
Console_Screen.cls #Clear the display area
print "Your guess is too high! ( valid range: 1 - 1000) Press Enter to continue."
Console_Screen.pause #Pause the game
end
$noOfGuesses +=1
break if $noOfGuesses > 10
end
end
#This method displays the information about the Ruby Number Guessing Game
def display_credits
Console_Screen.cls #Clear the display area
#Thank the player and display game information
puts "\t\tThank you playing the Ruby Number Guessing Game.\n\n\n\n"
puts "\n\t\t\t Developed by Jerry Lee Ford, Jr.\n\n"
puts "\t\t\t\t Copyright 2010\n\n"
puts "\t\t\tURL: http://www.tech-publishing.com\n\n\n\n\n\n\n\n\n\n"
end
end
# Main Script Logic -------------------------------------------------------
Console_Screen = Screen.new #Instantiate a new Screen object
SQ = Game.new #Instantiate a new Game object
#Execute the Game class's display_greeting method
SQ.display_greeting
answer = ""
$gameCount = 0
$noOfGuesses = 0
$totalNoOfGuesses = 0
$avgNoOfGuesses = 0
#Loop until the player enters y or n and do not accept any other input
loop do
Console_Screen.cls #Clear the display area
#Prompt the player for permission to start the game
print "Are you ready to play the Ruby Number Guessing Game? (y/n): "
answer = STDIN.gets #Collect the player's response
answer.chop! #Remove any extra characters appended to the string
#Terminate the loop if valid input was provided
break if answer == "y" || answer == "n" || answer == "c" #Exit loop
end
#Analyze the player's input
if answer == "n" #See if the player elected not to take the game
Console_Screen.cls #Clear the display area
#Invite the player to return and play the game some other time
puts "Okay, perhaps another time.\n\n"
else #The player wants to play the game
#Execute the Game class's display_instructions method
SQ.display_instructions
loop do
$gameCount+=1
#Execute the Game class's play_game method
SQ.play_game
$totalNoOfGuesses = $noOfGuesses * $gameCount
$avgNoOfGuesses = $totalNoOfGuesses / $noOfGuesses
print "The total number of guesses was #{$totalNoOfGuesses}"
print "The average number of guesses was #{$avgNoOfGuesses}"
Console_Screen.pause #Pause the game
print "Press Enter to continue"
Console_Screen.cls #Clear the display area
#Prompt the player for permission start a new round of play
print "Would you like to play again? (y/n): "
playAgain = STDIN.gets #Collect the player's response
playAgain.chop! #Remove any extra characters appended to the string
break if playAgain == "n" #Exit loop
end
#Call upon the Game class's determine_credits method in order to thank
#the player for playing the game and to display game information
SQ.display_credits
end
When running the code it says:
script-not-working.rb:74:in `block in play_game': undefined local variable or method `answer' for #<Game:0x0000000180f9c0> (NameError)
from script-not-working.rb:70:in `loop'
from script-not-working.rb:70:in `play_game'
from script-not-working.rb:181:in `block in <main>'
from script-not-working.rb:176:in `loop'
from script-not-working.rb:176:in `<main>'
So one solution could be make the variable answer global, adding $ before all answer variables it should look like : $answer. The code use other global variables so it could be fine for this. There are better practices than these but for this code it works fine. After that the game is running correctly. But it seems that has some other problems for evaluating the number. this should be another fix. maybe for another question. So investigate thought your code.
Here is the result of the code making answer global using $answer:
#Define a class representing the console window
class Screen
def cls #Define a method that clears the display area
puts ("\n" * 25) #Scroll the screen 25 times
puts "\a" #Make a little noise to get the player's attention
end
def pause #Define a method that pauses the display area
STDIN.gets #Execute the STDIN class's gets method to pause script
#execution until the player presses the enter key
end
end
#Define a class representing the Ruby Number Guessing Game
class Game
#This method displays the game's opening screen
def display_greeting
Console_Screen.cls #Clear the display area
#Display welcome message
print "\t\t Welcome to the Ruby Number Guessing Game!" +
"\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
"continue."
Console_Screen.pause #Pause the game
end
#Define a method to be used to present game instructions
def display_instructions
Console_Screen.cls #Clear the display area
puts "INSTRUCTIONS:\n\n" #Display a heading
#Display the game's instructions
puts "This game randomly generates a number from 1 to 100 and"
puts "challenges you to identify it in as few guesses as possible."
puts "After each guess, the game will analyze your input and provide"
puts "you with feedback. You may take as many turns as you need in"
puts "order to guess the game's secret number.\n\n"
puts "Game will stop if you have guessed 10 times.\n\n\n"
puts "Good luck!\n\n\n\n\n\n\n\n\n"
print "Press Enter to continue."
Console_Screen.pause #Pause the game
end
#Define a method that generates the game's secret number
def generate_number
#Generate and return a random number between 1 and 100
return randomNo = 1 + rand(1000)
end
#Define a method to be used control game play
def play_game
#Call on the generate_number method in order to get a random number
number = generate_number
#Loop until the player inputs a valid answer
loop do
Console_Screen.cls #Clear the display area
if $answer == "c"
print "Game count : #{$gameCount}"
end
#Prompt the player to make a guess
print "\nEnter your guess and press the Enter key: "
reply = STDIN.gets #Collect the player's answer
reply.chop! #Remove the end of line character
reply = reply.to_i #Convert the player's guess to an integer
#Validate the player's input only allowing guesses between 1 and 100
if reply < 1 or reply > 1000 then
redo #Redo the current iteration of the loop
end
#Analyze the player's guess to determine if it is correct
if reply == number then #The player's guess was correct
Console_Screen.cls #Clear the display area
print "You have guessed the number! Press enter to continue."
Console_Screen.pause #Pause the game
break #Exit loop
elsif reply < number then #The player's guess was too low
Console_Screen.cls #Clear the display area
print "Your guess is too low! ( valid range: 1 - 1000) Press Enter to continue."
Console_Screen.pause #Pause the game
elsif reply > number then #The player's guess was too high
Console_Screen.cls #Clear the display area
print "Your guess is too high! ( valid range: 1 - 1000) Press Enter to continue."
Console_Screen.pause #Pause the game
end
$noOfGuesses +=1
break if $noOfGuesses > 10
end
end
#This method displays the information about the Ruby Number Guessing Game
def display_credits
Console_Screen.cls #Clear the display area
#Thank the player and display game information
puts "\t\tThank you playing the Ruby Number Guessing Game.\n\n\n\n"
puts "\n\t\t\t Developed by Jerry Lee Ford, Jr.\n\n"
puts "\t\t\t\t Copyright 2010\n\n"
puts "\t\t\tURL: http://www.tech-publishing.com\n\n\n\n\n\n\n\n\n\n"
end
end
# Main Script Logic -------------------------------------------------------
Console_Screen = Screen.new #Instantiate a new Screen object
SQ = Game.new #Instantiate a new Game object
#Execute the Game class's display_greeting method
SQ.display_greeting
$answer = ""
$gameCount = 0
$noOfGuesses = 0
$totalNoOfGuesses = 0
$avgNoOfGuesses = 0
#Loop until the player enters y or n and do not accept any other input
loop do
Console_Screen.cls #Clear the display area
#Prompt the player for permission to start the game
print "Are you ready to play the Ruby Number Guessing Game? (y/n): "
$answer = STDIN.gets #Collect the player's response
$answer.chop! #Remove any extra characters appended to the string
#Terminate the loop if valid input was provided
break if $answer == "y" || $answer == "n" || $answer == "c" #Exit loop
end
#Analyze the player's input
if $answer == "n" #See if the player elected not to take the game
Console_Screen.cls #Clear the display area
#Invite the player to return and play the game some other time
puts "Okay, perhaps another time.\n\n"
else #The player wants to play the game
#Execute the Game class's display_instructions method
SQ.display_instructions
loop do
$gameCount+=1
#Execute the Game class's play_game method
SQ.play_game
$totalNoOfGuesses = $noOfGuesses * $gameCount
$avgNoOfGuesses = $totalNoOfGuesses / $noOfGuesses
print "The total number of guesses was #{$totalNoOfGuesses}"
print "The average number of guesses was #{$avgNoOfGuesses}"
Console_Screen.pause #Pause the game
print "Press Enter to continue"
Console_Screen.cls #Clear the display area
#Prompt the player for permission start a new round of play
print "Would you like to play again? (y/n): "
playAgain = STDIN.gets #Collect the player's response
playAgain.chop! #Remove any extra characters appended to the string
break if playAgain == "n" #Exit loop
end
#Call upon the Game class's determine_credits method in order to thank
#the player for playing the game and to display game information
SQ.display_credits
end
The problem is in your play_game method within the Game class, there is no where the variable answer is defined i.e assigned to a value, even an empty value. So i edited your script such that the method takes answer as an arguement, when the the method is called later here, you pass the answer expected from the console as its argument.
SQ.play_game answer
Here is the edited script below
#Define a class representing the console window
class Screen
def cls #Define a method that clears the display area
puts ("\n" * 25) #Scroll the screen 25 times
puts "\a" #Make a little noise to get the player's attention
end
def pause #Define a method that pauses the display area
STDIN.gets #Execute the STDIN class's gets method to pause script
#execution until the player presses the enter key
end
end
#Define a class representing the Ruby Number Guessing Game
class Game
#This method displays the game's opening screen
def display_greeting
Console_Screen.cls #Clear the display area
#Display welcome message
print "\t\t Welcome to the Ruby Number Guessing Game!" +
"\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
"continue."
Console_Screen.pause #Pause the game
end
#Define a method to be used to present game instructions
def display_instructions
Console_Screen.cls #Clear the display area
puts "INSTRUCTIONS:\n\n" #Display a heading
#Display the game's instructions
puts "This game randomly generates a number from 1 to 100 and"
puts "challenges you to identify it in as few guesses as possible."
puts "After each guess, the game will analyze your input and provide"
puts "you with feedback. You may take as many turns as you need in"
puts "order to guess the game's secret number.\n\n"
puts "Game will stop if you have guessed 10 times.\n\n\n"
puts "Good luck!\n\n\n\n\n\n\n\n\n"
print "Press Enter to continue."
Console_Screen.pause #Pause the game
end
#Define a method that generates the game's secret number
def generate_number
#Generate and return a random number between 1 and 100
return randomNo = 1 + rand(1000)
end
#Define a method to be used control game play
def play_game answer
#Call on the generate_number method in order to get a random number
number = generate_number
#Loop until the player inputs a valid answer
loop do
Console_Screen.cls #Clear the display area
if answer == "c"
print "Game count : #{$gameCount}"
end
#Prompt the player to make a guess
print "\nEnter your guess and press the Enter key: "
reply = STDIN.gets #Collect the player's answer
reply.chop! #Remove the end of line character
reply = reply.to_i #Convert the player's guess to an integer
#Validate the player's input only allowing guesses between 1 and 100
if reply < 1 or reply > 1000 then
redo #Redo the current iteration of the loop
end
#Analyze the player's guess to determine if it is correct
if reply == number then #The player's guess was correct
Console_Screen.cls #Clear the display area
print "You have guessed the number! Press enter to continue."
Console_Screen.pause #Pause the game
break #Exit loop
elsif reply < number then #The player's guess was too low
Console_Screen.cls #Clear the display area
print "Your guess is too low! ( valid range: 1 - 1000) Press Enter to continue."
Console_Screen.pause #Pause the game
elsif reply > number then #The player's guess was too high
Console_Screen.cls #Clear the display area
print "Your guess is too high! ( valid range: 1 - 1000) Press Enter to continue."
Console_Screen.pause #Pause the game
end
$noOfGuesses +=1
break if $noOfGuesses > 10
end
end
#This method displays the information about the Ruby Number Guessing Game
def display_credits
Console_Screen.cls #Clear the display area
#Thank the player and display game information
puts "\t\tThank you playing the Ruby Number Guessing Game.\n\n\n\n"
puts "\n\t\t\t Developed by Jerry Lee Ford, Jr.\n\n"
puts "\t\t\t\t Copyright 2010\n\n"
puts "\t\t\tURL: http://www.tech-publishing.com\n\n\n\n\n\n\n\n\n\n"
end
end
# Main Script Logic -------------------------------------------------------
Console_Screen = Screen.new #Instantiate a new Screen object
SQ = Game.new #Instantiate a new Game object
#Execute the Game class's display_greeting method
SQ.display_greeting
answer = ""
$gameCount = 0
$noOfGuesses = 0
$totalNoOfGuesses = 0
$avgNoOfGuesses = 0
#Loop until the player enters y or n and do not accept any other input
loop do
Console_Screen.cls #Clear the display area
#Prompt the player for permission to start the game
print "Are you ready to play the Ruby Number Guessing Game? (y/n): "
answer = STDIN.gets #Collect the player's response
answer.chop! #Remove any extra characters appended to the string
#Terminate the loop if valid input was provided
break if answer == "y" || answer == "n" || answer == "c" #Exit loop
end
#Analyze the player's input
if answer == "n" #See if the player elected not to take the game
Console_Screen.cls #Clear the display area
#Invite the player to return and play the game some other time
puts "Okay, perhaps another time.\n\n"
else #The player wants to play the game
#Execute the Game class's display_instructions method
SQ.display_instructions
loop do
$gameCount+=1
#Execute the Game class's play_game method
SQ.play_game answer
$totalNoOfGuesses = $noOfGuesses * $gameCount
$avgNoOfGuesses = $totalNoOfGuesses / $noOfGuesses
print "The total number of guesses was #{$totalNoOfGuesses}"
print "The average number of guesses was #{$avgNoOfGuesses}"
Console_Screen.pause #Pause the game
print "Press Enter to continue"
Console_Screen.cls #Clear the display area
#Prompt the player for permission start a new round of play
print "Would you like to play again? (y/n): "
playAgain = STDIN.gets #Collect the player's response
playAgain.chop! #Remove any extra characters appended to the string
break if playAgain == "n" #Exit loop
end
#Call upon the Game class's determine_credits method in order to thank
#the player for playing the game and to display game information
SQ.display_credits
end

Ruby script need fix

I'm having a problem with my ruby script. If anyone could help, I'd really appreciate it. The problem is that the number is stuck between 1-2; where 2 is too high and 1 is too low. The guesses should be integers only.
#!/usr/bin/ruby
def highLow(max)
again = "yes"
while again == "yes"
puts "Welcome to the High Low game"
playGame(max)
print "Would you like to play again? (yes/no): "
again = STDIN.gets.chomp
if again == 'no'
puts "Have a nice day, Goodbye"
end
end
end
#This method contains the logic for a single game and call the feedback method.
def playGame(max)
puts "The game gets played now"
puts "I am thinking of a number between 1 and #{max}." #It show what chosen by user
randomNumber = rand(max)+ 1
print "Make your guess: "
guess = STDIN.gets.chomp
feedback(guess, randomNumber)
end
#Start while loop
#Logic for feedback method. It's ganna check the guess if it's high or low.
def feedback(guess, randomNumber)
count = 1
while guess.to_i != randomNumber
count = count + 1
if guess.to_i < randomNumber
print "That's too low. Guess again: "
else
print "That's too high. Guess again: "
end
guess = STDIN.gets.chomp
end
puts "Correct! You guessed the answer in #{count} tries!"
end
highLow(ARGV[0])
Change your last line to this:
highLow(ARGV[0].to_i)
The ARGV array contains all the passed in arguments as strings, so you have to cast it to integer.

Guessing Game Ruby

So i have been learning ruby as of late and i am working on this code for practice purposes but i cannot seems to be able to solve this problem any help would be appreciate it.
This is are the guidelines i am following:
clear the screen
greet the player
explain the rules of the game to the player
generate a random number between 0 and x (x being a variable that can be set to any integer)
allow the player n number of guesses (n being a variable)
keep track of the guess history
don't count repeated guesses against the player
congratulate the player when he/she guesses correctly
alert the player when there is only one guess remaining
print the guess history at the end of the game
count number of games won IN A ROW
count number of games won in total
congratulate the play on 3 games won IN A ROW
ask if the player wants to play again
thank the player for playing games if the number of games played is greater than 2
please keep in my that this is work in progress and i have not completed all the guideline, however my questions is with one particular part of it.
here is the code:
guess = Array.new
puts guess.class
def ask()
puts "Please answer in a 'y' or 'n' only!"
puts "Would like to play again?"
end
def guess_check_against()
g = guess.last
unless guess.include?(g) != guess
count+=1
else
puts "sorry you have guessed that number before, Guess Again: "
guess << gets.to_i
count+=1
end
end
puts "what is your name?"
user= gets.chomp
puts "Hello #{user}!!"
max_user_attempts = 4
#attempt_counter = 0
directions = "\nLets play a guessing game! You have
#{max_user_attempts.to_s} guesses before you lose."
print directions
g = guess.last
win = 0
count = 0
play = true
while play == true
puts "Please tell me the max value of the random number: "
max= gets.to_i
num= rand(max)
puts "Ok. The random number is generated between 1 and " + max.to_s + "."
puts "Make your guess: "
guess << gets.to_i
guess_check_against()
#attempt_counter+=1
while guess != num && play != false
if g > num && #attempt_counter < max_user_attempts
print "That's too high. Guess again: "
guess << gets.to_i
guess_check_against()
#attempt_counter+=1
elsif g < num && #attempt_counter < max_user_attempts
print "That's too low. Guess again: "
guess << gets.to_i
guess_check_against()
count+=1
#attempt_counter+=1
else
break
end
end
if #attempts_counter >= max_user_attemtps
puts "Sorry! you lost! Try Again"
break
else #attempts_counter <= max_user_attempts
puts "Correct! You guessed the answer in " + count.to_s + " tries!"
win+=1
end
if win >= 3
puts "Congratulation! you have #{win} number of games in a row"
ask()
answer = gets.chomp!
elsif win < 3
ask()
answer = gets.chomp!
else
break
end
if answer == 'n'
play = false
break
end
if answer == 'y'
play = true
count = 0
end
end
puts "Ok. Goodbye!!"
and here is the error i keep receiving when i try to run this program:
guessing_game.rb:12:in `guess_check_against': undefined local variable or method `guess' for main:Object (NameError)
from guessing_game.rb:45:in `<main>'
when i try to use irb to run the same scenario it works completely fine.
i can not figure out what i am doing wrong, please help!!
The method definition
def guess_check_against()
g = guess.last
...
end
has its own scope, and the local variable
guess = Array.new
that you defined outside of it, is not accessible inside the method definition. guess is not defined inside the method definition. You can change the code so that the method takes that as an argument, and it will become accessible.

Basic High/Low Program Ruby Input Request

I have been trying to figure out how to make it so that the user can only enter a positive whole number between 1 and 100 for this simple High/Low guess game. I would like it so anything other then a whole number between 1 and 100 will inform the user they can't do that for all inputs. Is there a simple way to do this?
What I have now:
count=0
play = true
while play == true
print "Give me a random number between 1 and 100: "
max= gets.to_i
num= rand(max)
puts "Now guess between 1 and " + max.to_s +
"."
print "What is your guess?: "
guess=gets.to_i
while guess != num && play != false
if guess > num
print "Too high! "
guess=gets.to_i
count+=1
elsif guess < num
print "Too low! "
guess=gets.to_i
count+=1
else
break
end
end
puts "Good Job! You figured it out in " + count.to_s + " attempts!"
print "Want to try again? y/n "
answer=gets.chomp!
if answer == 'n'
play = false
break
end
if
answer == 'y'
play = true
end
end
puts "Maybe next time..."
The easiest way to do that is to use a regular expression and a range.
guess = gets.chomp
if(guess =~ /\A\d+\Z/ && (1..100) === guess.to_i)
#do stuff
else
puts "Please enter a valid number"
end
The regular expression ensures that we get an input composed only of digits (a whole number) and the ranged checks to see if it is between 1 and 100.
if (1..100).include?(guess) && 0 == guess % 1
# ...
end

Resources