Ruby Hangman - 如何找到数组中匹配字母的索引

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

Ruby菜鸟。尝试构建一个 hangman 游戏并使用以下代码查找索引,以便在玩家猜对时用猜到的字母替换破折号。这些词来自 json 数据库。这里添加@letter和@word作为示例,使用实例变量是因为我在完整代码中是def方法。

知道为什么这不起作用吗? 'find_index' return 可以为它找到字母的每个地方设置多个值吗?如果 'find_index' 没有 return 多个值,是否有一个数组方法可以做到?

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

您似乎想要 @word 中所有字符的索引用于 @letter。如果是这种情况,那么以下应该有效:

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

正在分解...

  • #chars returns单词中字符的数组
  • #each_with_index returns 产生字符和迭代索引的 Enumerator
  • #select用于过滤数组为character:index对,其中字符匹配@letter
  • #map 迭代过滤后的 character:index 对数组和 returns 每对的最后一个元素(即索引)。