Skip to content

Instantly share code, notes, and snippets.

@tenebrousedge
Last active April 28, 2017 16:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tenebrousedge/5014c4ab6793cfecaee90c43ff6da7c5 to your computer and use it in GitHub Desktop.
#!/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} "}
return puts "Congratulations! You win!" if word & guessed == word
tries_left -= 1
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment