Home > Enterprise >  Ruby Hangman - how to find the index of a matching letter in an array
Ruby Hangman - how to find the index of a matching letter in an array

Time:03-29

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}"

CodePudding user response:

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 receives iterates the filtered array of character:index pairs and returns the last element for each pair (i.e. the index).

CodePudding user response:

You can use delimiter in split(), so you can split word into substrings based on it and return an array of these substrings. "elephant".split(//)

Then, having the index, you can call this index on the array word[0] and get the desired letter.

word = "elephant"
letter = "e"
word = word.split(//) # => ["e", "l", "e", "p", "h", "a", "n", "t"]
index = word.find_index(letter) # => 0
puts "the index of letter #{letter} is #{index}" #>> the index of letter e is 0
# or
puts "the letter at index 0 is #{word[0]}"  #>> letter at index 0 is e

Can 'find_index' return multiple values for every place it finds the letter?

No, it returns the index of the first object in array for which the block returns true. Here about find_index()

If 'find_index' doesn't return multiple values is there an array method which does?

You can try find_all() with block:

indices = (0 ... word.length).find_all { |i| word[i] == letter } # => [0, 2]
  • Related