Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class GuessTheNumber
def play
@nnn = 1.upto(100).to_a.sample
# play game
puts "Alright, I have a number in mind from 1-100. Pick a number."
guess = gets.chomp
puts "You said #{guess}."
attempt guess
end
def play_again?
response = ""
puts "Do you want to play again? [y/n]"
until response == "y" or response == "n"
response = gets.chomp
end
#response == "y"
response.eql? "y"
end
def attempt guess
guess = guess.to_i
if guess < @nnn
puts "#{guess} is too low. Try again:"
new_guess = gets.chomp
attempt new_guess
elsif guess > @nnn
puts "#{guess} is too high. Try again:"
new_guess = gets.chomp
attempt new_guess
elsif guess == @nnn
puts "Yes, the answer is #{@nnn}. Aren't you proud of yourself?"
end
end
end
# main
g = GuessTheNumber.new
keep_playing = true
while keep_playing
g.play
keep_playing = g.play_again?
end
@syntacticsugar
Copy link
Author

syntacticsugar commented May 27, 2014

here's my previous version.

class GuessTheNumber
  def initialize
    @nnn = 1.upto(100).to_a.sample
    puts "Alright, I have a number in mind from 1-100.  Pick a number."
    guess = gets.chomp
    puts "You said #{guess}."
    attempt guess
  end

  def attempt guess
    guess = guess.to_i

    if guess < @nnn
      puts 'Your guess was too low.  Try again:'
      new_guess = gets.chomp
      attempt new_guess
    elsif guess > @nnn
      puts 'Your guess was too high.  Try again:'
      new_guess = gets.chomp
      attempt new_guess
    elsif guess == @nnn
      puts "Yes, the answer is #{@nnn}. Aren't you proud of yourself?"
    end
  end
end

g = GuessTheNumber.new

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment