Question on Hangman RSPEC03 - ComputerPlayer#handle_response

Hey Guys,

Was reviewing and refactoring some of my code and had a question on the Hangman project. Specifically for ComputerPlayer#handle_response. Rspec has the following test (third test of Hangman_03_spec.rb):

  it "correctly handles the response after registering secret length" do
    guesser = ComputerPlayer.new(["leer", "reel", "real", "rear"])
    guesser.register_secret_length(4)

    guesser.handle_response("r", [0])

    expect(guesser.candidate_words.sort).to eq(["reel","real"].sort)
  end

If I’m reading it correctly, why isn’t rear part of the candidate word list? I’m asking because the initial method I wrote for ComputerPlayer#handle_response checks the indices of the candidate words to see if they match the letter_guess. See following code:

  def handle_response(letter_guess,index_found)
    @candidate_words.select! do |word|
      possible_word=true
      index_found.each do |idx|
        possible_word=false if word[idx]!=letter_guess
      end
      possible_word
    end
    @candidate_words
  end

When I check it against the RSPEC, it errors out as follows since it evaluate true that reel, rear, and reel has “r” at the 0th index position:

  1) Phase III ComputerPlayer #handle_response correctly handles the response after registering secret length
     Failure/Error: expect(guesser.candidate_words.sort).to eq(["reel","real"].sort)

       expected: ["real", "reel"]
            got: ["real", "rear", "reel"]

       (compared using ==)
     # ./spec/hangman_03_spec.rb:48:in `block (4 levels) in <top (required)>'

I took a look at the solution and refactor my method to check each character of the candidate word to see if the index found and the letter guess matched:

  def handle_response(letter_guess,index_found)
    @candidate_words.select! do |word|
      possible_word=true
      word.split("").each_with_index do |ch,idx|
        if index_found.include?(idx) && ch!=letter_guess
          possible_word=false
        elsif ch==letter_guess && index_found.include?(idx)==false
          possible_word=false
        end
      end
      possible_word
    end
    @candidate_words
  end

Trying to figure out why wouldn’t my first method pass the tests. Thanks!

Hi Rabite,

The example in the spec is assuming that when you guess “r”, the game will tell you that r is only found at the 0th index of the word. That allows you to rule out “rear”, because if “rear” were the word we’re looking for, then the game’s response would’ve been [0, 3]. The second method you have accounts for that, whereas the first one, the one that fails the spec, doesn’t. Does that make sense?

Best,

Matthias

Yeah, that make sense. Thanks! Misread it and didn’t notice it was only at that index.