0

My goal is to create a game of hangman. I wrote code similar to this:

c = []
players_guess = gets
b = "example"
b.scan(/./) {|letter| c << letter}

c.each do |letter|
  if letter == players_guess
    puts letter
  else
    puts "*"
  end
end  

The code checks if the player guessed the right letter from the password hidden in variable c, and then displays the password hidden behind the *s and only revealed guessed letters. But when I run the program, the result is always the same, it displays players_guess, and then gives seven *. What is wrong here?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Leo
  • 2,061
  • 4
  • 30
  • 58
  • What is wrong is your expectation that something different would happen :) What hint do you need? – Mark Thomas Dec 19 '12 at 02:10
  • i expected eg if players_guess = "e" it will display "e*****e". but it gives "e*******". and it displays the players_guess at the beginning like this no matter what letter or number i choose:( – Leo Dec 19 '12 at 02:15

2 Answers2

1

Here's a simple way to do what you want:

word = "example"
puts "Type a letter: "
guess = gets.chomp
puts word.tr("^#{guess}", "*")

This uses the String#tr method to replace all but the guess to *.

The output if you typed e would be e*****e.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
0

Your If/Then Logic is Wrong

Your code is as follows:

c.each do |letter|
  if letter == players_guess
    puts letter
  else
    puts "*"
  end
end

The conditional will generally be false, since no single letter is likely to match the entire line retrieved by gets. As a result, you get an asterisk printed for each letter in c.

Some Options to Fix Your Code

You can do a couple of things here.

  1. Just show the string if the strings are equal.

    puts players_guess if b == players_guess.chomp
    
  2. Use a counter in your loop to index into your arrays or strings.

  3. Split both strings into an array, and compare the arrays, printing letters that match or an asterisk on a non-match.

    c.each_with_index do |char, idx|
      puts char == players_guess.scan(/./)[idx] ? char : '*'
    end
    
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • i don't know the methods you used here, but thanks anyway, i will do my best researching:) – Leo Dec 19 '12 at 02:21