Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. def hangman
  4. tries_left = 12
  5. # only select words less than ten letters long
  6. lines = File.readlines('/usr/share/dict/words').select { |e| e.length < 10 }
  7. # grab a random word
  8. word = lines[rand(lines.length)].chomp.chars
  9. guessed = []
  10. while tries_left > 0
  11. print "Guess a letter : "
  12. # only take the first character.
  13. # we could check to see if it's a letter, but why?
  14. guessed.push STDIN.gets.chomp.chars[0]
  15. # prints the letter or an underscore
  16. # the ternary could have been part of #reduce but the line is long enough as is
  17. puts word.
  18. map { |e| guessed.include?(e) ? e : '_'}.
  19. reduce('') { |acc, e| acc += " #{e} "}
  20. tries_left -= 1
  21. return puts "Congratulations! You win!" if word & guessed == word
  22. puts "You have #{tries_left} guesses left"
  23. end
  24. puts "Sorry, you lose. The word was #{word.join}"
  25. end
  26.  
  27. loop do
  28. hangman
  29. print "Rematch? [y/N]"
  30. break unless gets.chomp.casecmp?('y')
  31. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement