Why .select is my new jam

I got a new story this week to build a Hangman game and I am pretty excited! In case you’ve forgotten, at the start of the game you get presented with some lines and each line represents a letter from a word. Your job is to guess the letters in the word in less than a certain amount of guesses. Each time you get a letter wrong, a body part of a stick man is drawn. Once your guesses are up, the head, arms, legs and body of a stickman have been drawn and the man is hung. It’s all very distressing.

I built a few different parts that I needed for my game but then I hit a bit of a stumbling point *queue the onset of code-face* .

I needed to find a way of getting the index positions of all instances of a certain letter in my array. For example:

array = ["a", "a"] -> [0, 1]

However, when I called .index(“a”) on my array, only the first index position of “a” was returned.

I needed to find a way of getting all the index positions of “a”.

After much trial and error, which mainly resulted in more error, I did some research and I came across a method I thought would work. I was introduced to the method .select which uses a condition passed to it and returns an array of anything that matches that condition.

In my method, I am passing in the player’s letter guess, let’s say it’s “a”, the spaces of a word [“_”, “_”, “_”] and the word itself “baa”.

def substitute_letters(guess, word_places, word)
  letter_position = (0..word.length-1).select {|i| word[i] == guess}

letter_position.each do |index|
word_places[index] = guess

I created a range from the first letter to the last letter in my word and used .select with a condition that used index positions to lookup letter values and returned the index positions of any letter values that matched the guess value “a” in a new array. This returned exactly what I needed.

I then stored this new array of index positions in a variable called letter_position and used a loop on my letter_position array so I could use each index position with the corresponding index position on my word_places array to replace the blank line value at each index position of my word_places array with the guessed letter.

So far, this seems to do what I need.