Skip to content

Instantly share code, notes, and snippets.

@syntacticsugar
Created May 27, 2014 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syntacticsugar/117fc6c29c99b26e2e64 to your computer and use it in GitHub Desktop.
Save syntacticsugar/117fc6c29c99b26e2e64 to your computer and use it in GitHub Desktop.
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

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