Ruby script crashes [closed] - ruby

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

Related

Having trouble interpolating user input into another method

Im scraping data from espn.com of all golden state warriors players and want to show each attribute of every player. Such as their height position, salary and college. Once I give the user the ability to pick the player they would like to know more about. I would like puts out that information for the user to see but I see an error in the process.
This is the code I have written.
attr_accessor :player, :continue
def intialize
#continue = true
end
def call
start
#skips over while loop
#while #continue
list_players
menu
show_player if #continue == true && #player != nil
#end
goodbye
end
def start
puts "Welcome to the Golden State Roster 'The Home Of The Splash Brothers'"
end
def goodbye
puts "See you next time for any players updates!"
end
def list_players
Player.all.clear
Scraper.scrape_page
Player.all.each.with_index(1) do |player, index|
puts "#{index}. #{player.name}"
end
end
def menu
input = ""
while input != "exit"
puts "Choose any player you wish by the 'number', type 'list' to reshow list or type 'exit' when finished."
input = gets.strip.downcase
if input.to_i > 0
the_player = #player[input.to_i - 1]
puts "#{the_player.name} plays #{the_player.position} for the Golden State Warriors. He is #{the_player.age} years old and #{the_player.height} tall. He comes in weighing #{the_player.weight}. #{the_player.name} graduated from #{the_player.college} and makes honest living of #{the_player.salary} dollars per year."
"Select another player by typing 'yes' or press 'exit' when you're ready to leave."
binding.pry
elsif input == "exit"
#continue = false
# elsif input.to_i.between?(1, Player.all.length)
# #player = Player.all[input.to_i - 1]
elsif input == "list"
list_players
else
puts "Error, Choose any player you wish by the number or type 'exit' when finished."
end
end
end ```
It breaks at "the_player"
```This is the error
```Welcome to the Golden State Roster 'The Home Of The Splash Brothers'
1. Jordan Bell
2. Andrew Bogut
3. Quinn Cook
4. DeMarcus Cousins
5. Stephen Curry
6. Marcus Derrickson
7. Kevin Durant
8. Jacob Evans
9. Draymond Green
10. Andre Iguodala
11. Jonas Jerebko
12. Damian Jones
13. Damion Lee
14. Shaun Livingston
15. Kevon Looney
16. Alfonzo McKinnie
17. Klay Thompson
Choose any player you wish by the 'number', type 'list' to reshow list or type 'exit' when finished.
4
Traceback (most recent call last):
2: from ./bin/ballers:6:in `<main>'
1: from /home/Thisforbliss/Development/project/lib/project/cli.rb:17:in`call'
/home/Thisforbliss/Development/project/lib/project/cli.rb:45:in `menu': undefined method `[]' for nil:NilClass (NoMethodError)```

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

calculate total number of guesses in number guessing game 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"

Dynamic constant assignment Ruby [duplicate]

This question already has answers here:
Dynamic constant assignment
(7 answers)
Closed 2 years ago.
I have been following a tutorial to create a typing challenge. I have taken care to follow this carefully. When i try to run the script from the command line i keep getting the following error and i do not understand it. I think the tutorial might be quite old but if someone could give me some guidance to understand it so i can fix it then that would be so appreciated! The error i get when i run the script from the command line is as follows....
Typechallenge.rb:89: dynamic constant assignment
Console_Screen = Screen.new
^
typechallenge.rb:90: dynamic constant assignment
Typing_Test = Test.new
The script itself is below...
#Script name: Typing Challenge
#Description: Demonstrating how to apply conditional logic in order to analyze user input and control
#the execution of the script through a computer typing test.
class Screen
def cls
puts ("\n" * 25)
puts "\a"
end
def pause
STDIN.gets
end
end
class Test
def display_greeting
Console_Screen.cls
print "\t\t Welcome to the Typing Challenge" +
"\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
"continue. \n\n: "
Console_Screen.pause
end
def display_instructions
Console_Screen.cls
puts "\t\t\tInstructions:\n\n"
puts %Q{ This test consists of five typing challenges. Each sentence is a challenge and are presented one at a time. To respond
correctly you should retype each sentence exactly as it is shown and the press the Enter key. Your grade will be displayed at
the end of the test.\n\n\n\n\n\n\n\n\n
Press Enter to continue.\n\n}
Console_Screen.pause
End
def present_test(challenge)
Console_Screen.cls
print challenge + "\n\n: "
result = STDIN.gets
result.chop!
if challenge == result then
$noRight += 1
Console_Screen.cls
print "Correct!\n\nPress Enter to continue."
Console_Screen.pause
else
Console_Screen.cls
print "Incorrect!\n\nPress Enter to continue."
Console_Screen.pause
end
end
def determine_grade
Console_Screen.cls
if $noRight >= 3 then
print "You retyped " + $noRight.to_s + " sentence(s) correctly. "
puts "You have passed the typing test!\n\nPress Enter to continue."
else
print "You retyped " + $noRight.to_s + " sentence(s) correctly. "
puts "You have failed the typing test!\n\nPress Enter to continue."
end
end
#Main script logic
$noRight = 0
Console_Screen = Screen.new
Typing_Test = Test.new
Typing_Test.display_greeting
Console_Screen.cls
print "Would you like to test your typing skills? (y/n)\n\n: "
answer = STDIN.gets
answer.chop!
until answer == "y" || answer == "n"
Console_Screen.cls
print "Would you like to test your typing skills? (y/n)\n\n: "
answer = STDIN.gets
answer.chop!
end
#Analyzing the players response
if answer == "n"
Console_Screen.cls
puts "Okay, perhaps another time! \n\n"
else
Typing_Test.display_instructions
Typing_Test.present_test "In the end there can be only one"
Typing_Test.present_test "Once upon a time a great plague swept across the land"
Typing_Test.present_test "Welcome to the typing challenge"
Typing_Test.present_test "There are very few problems in the world" + "that enough M&Ms cannot fix."
Typing_Test.present_test "Lets play this game of life together"
Typing_Test.determine_grade
Console_Screen.pause
Console_Screen.cls
puts "Thank you for playing the game!\n\n"
end
end
end
Names that start with upper-case letter are constants. In your code you assign a non-constant (dynamic) value to a name that represents a constant. Hence the error.
Console_Screen = Screen.new
Use local variable name convention (snake_case)
console_screen = Screen.new

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.

Resources