public
Created

Number guessing game for nubies

  • Download Gist
guess.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.