Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- def hangman
- tries_left = 12
- # only select words less than ten letters long
- lines = File.readlines('/usr/share/dict/words').select { |e| e.length < 10 }
- # grab a random word
- word = lines[rand(lines.length)].chomp.chars
- guessed = []
- while tries_left > 0
- print "Guess a letter : "
- # only take the first character.
- # we could check to see if it's a letter, but why?
- guessed.push STDIN.gets.chomp.chars[0]
- # prints the letter or an underscore
- # the ternary could have been part of #reduce but the line is long enough as is
- puts word.
- map { |e| guessed.include?(e) ? e : '_'}.
- reduce('') { |acc, e| acc += " #{e} "}
- tries_left -= 1
- return puts "Congratulations! You win!" if word & guessed == word
- puts "You have #{tries_left} guesses left"
- end
- puts "Sorry, you lose. The word was #{word.join}"
- end
- loop do
- hangman
- print "Rematch? [y/N]"
- break unless gets.chomp.casecmp?('y')
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement