Skip to content

@jeremyw /guess.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Number guessing game for nubies
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
Something went wrong with that request. Please try again.