0

Ruby noob. Trying to build a hangman game and use the following code to find the index so I can replace the dashes with the guessed letter when a players guesses correctly. The words are from a json database. @letter and @word are added here as an example, and instance variables are used because I'm def methods in the full code.

Any ideas why this is not working? Can 'find_index' return multiple values for every place it finds the letter? If 'find_index' doesn't return multiple values is there an array method which does?

@word = "elephant"
@letter = "e"
@word = @word.split
@index = @word.find_index(@letter)
puts "the index is #{@index}"

1 Answers1

1

It seems you want indices for all characters in @word for @letter. If this is the case, then the following should work:

@word.chars.each_with_index.select { |c, i| c == @letter }.map(&:last)

Breaking this down...

  • #chars returns an array of the characters in the word
  • #each_with_index returns an Enumerator that yields the character and the iteration index
  • #select is used to filter the array to character:index pairs, where the character matches @letter
  • #map iterates over the filtered array of character:index pairs and returns the last element for each pair (i.e. the index).
Tim Lowrimore
  • 2,024
  • 1
  • 17
  • 9