Created
December 3, 2011 19:17
-
-
Save jeremyw/1427874 to your computer and use it in GitHub Desktop.
Number guessing game for nubies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def sum | |
inject(0) { |sum, value| sum += value } | |
end | |
def average | |
sum.to_f / size | |
end | |
end | |
def play_game(max=100) | |
number = rand(max) + 1 | |
count = 0 | |
puts "Guess a number between 1 and #{max}" | |
while true do | |
guess = gets.to_i | |
count += 1 | |
if guess == number | |
puts "You got it in #{count} guesses!" | |
return count | |
elsif guess < number | |
puts "Too low" | |
elsif guess > number | |
puts "Too high" | |
end | |
end | |
end | |
def want_to_play? | |
puts "Do you want to play a game? (y/n)" | |
play = gets.strip | |
play != 'n' | |
end | |
guess_counts = [] | |
while want_to_play? do | |
guess_counts << play_game(10) | |
end | |
# show me the average # of guesses | |
puts guess_counts.average |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment