多个索引阵列 - 红宝石

发布于 2025-02-12 09:56:16 字数 497 浏览 2 评论 0 原文

我有一个游戏的项目,如果选择的字母在秘密单词中存在,则需要给选择的字母留下深刻的印象,但是当我试图捕获选择字母的索引时,例如“ A”,例如秘密单词“ programador,代码使我返回“ programador”一词的所有索引,不仅是字母“ a”存在的索引。

palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada

palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array.each_with_index.select { |letra_procurada, index| 
  total_encontrado >= 1 
}.map { |pair| pair[1] }

此代码正在返回我:0 1 2 3 4 5 6 7 8 9 10 10

i have a project of a game, in it i need to impress the letter selected if the letter selected is present in the secret word, but when i try to catch the index of the select letter, like "a", in the secret word "programador, the code returns me all the index of the word "programador" not only the index where the letter "a" is present.

palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada

palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array.each_with_index.select { |letra_procurada, index| 
  total_encontrado >= 1 
}.map { |pair| pair[1] }

this code is returning me: 0 1 2 3 4 5 6 7 8 9 10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

若水微香 2025-02-19 09:56:17

在您的代码中, total_encontrado 2 ,它大于或等于 1 。结果,您给出 #select 的条件始终是正确的,因此它选择了每个字符的索引。然后,您将其映射到索引。

相反,您可能只想选择匹配 letra_procurada 的字母。

palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada

palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array
     .each_with_index
     .select { |letra, index| letra_procurada == letra }
     .map { |pair| pair[1] }

您也可以使用 #FILTER_MAP (Ruby 2.7及以后)来简化这一点。

palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada

palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array
     .each_with_index
     .filter_map { |letra, index| index if letra_procurada == letra }

In your code, total_encontrado is 2, which is greater than or equal to 1. As a result, the condition you give to #select is always true, so it selects every character with its index. You then map that to just the indices.

Instead, you likely want to select only the letters that match letra_procurada.

palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada

palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array
     .each_with_index
     .select { |letra, index| letra_procurada == letra }
     .map { |pair| pair[1] }

You could also use #filter_map (Ruby 2.7 and later) to simplify this.

palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada

palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array
     .each_with_index
     .filter_map { |letra, index| index if letra_procurada == letra }
腻橙味 2025-02-19 09:56:17

选择条款中的条件对于每个索引都是正确的,因为它仅检查 total_encontrado 变量,并且该值不会在每次迭代中更改。

puts palavra_secreta_array
  .each_with_index
  .select { |letra_procurada, index| total_encontrado >= 1 }
#                                    ^^^^^^^^^^^^^^^^^^^^^
  .map { |pair| pair[1] }

您想要的是选择匹配猜测字符的索引,因此您的条件可以做到这一点:

puts palavra_secreta_array
  .each_with_index
  .select { |letra, index| letra == letra_procurada }
  .map { |pair| pair[1] }

请注意,我必须将第一个参数的名称更改为 select block。您已经在那里重复使用 letra_procurada ,但这将具有 shadowing 实际 letra_procurada 变量。请记住,选择正在调用数组中每个元素的块,并且选择仅该块返回true的元素,因此块的第一个参数是元素从数组中,如果您阴影或忽略它,您将不知道在块内部处理什么。

您还可以将其缩小一点,然后跳过 split ,以使用 string#enter_char

puts palavra_secrata
    .each_char
    .with_index
    .select { |c, _| c == letra_procurada }
    .map(&:last)

The condition inside your select clause will be true for every index, since it only checks the total_encontrado variable and that value will not change in each iteration.

puts palavra_secreta_array
  .each_with_index
  .select { |letra_procurada, index| total_encontrado >= 1 }
#                                    ^^^^^^^^^^^^^^^^^^^^^
  .map { |pair| pair[1] }

What you want is to select the indexes that match the guessed character, so your condition could do that instead:

puts palavra_secreta_array
  .each_with_index
  .select { |letra, index| letra == letra_procurada }
  .map { |pair| pair[1] }

Note that I had to change the name of the first parameter to the select block. You had re-used letra_procurada there, but that would have the effect of shadowing the actual letra_procurada variable. Remember that select is calling the block for each element in the array and selecting only the elements for which the that block returns true, so the first parameter to the block is the element from the array and, if you shadow or ignore it, you'll have no idea what you're dealing with inside the block.

You can also slim this down a bit more and skip the split in favor of using String#each_char:

puts palavra_secrata
    .each_char
    .with_index
    .select { |c, _| c == letra_procurada }
    .map(&:last)
烟花易冷人易散 2025-02-19 09:56:17

“ letra_procurada” 是指“字母想要”,因此您似乎必须印象 pass 您想要选择的元素:

letra_procurada = "a"

palavra_secreta_array.each_with_index.select { |letra_procurada, index| }
#                                               ^^^^^^^^^^^^^^^

但是这根本不是阻止参数或特别是选择的方式。如果您将 letra_procurada 用字符串字面替换,则您将获得 syntaxerror 右away:

palavra_secreta_array.each_with_index.select { |"a", index| }
# SyntaxError: unexpected string literal

一个块包含您传递块的方法,该方法将块传递到(这里:<代码>选择)可以调用(多次,一次或根本只有一次)。在每个块调用时, | letra_procurada,index | )将从中传递 the方法(ie select> select> select 块。

您调用选择,但选择调用块。这也被称为“ “ noreferrer”> callback ”。

在您的示例中,选择调用每个元素的块,并将该元素作为块参数 letra_procurada index 。然后,它希望该块返回 true false 。该返回值确定该元素是否包含在结果中。

由于该块的第一个参数可以是任何字母,因此您可能需要一个更通用的变量名称。这样的事情:

palavra_secreta_array.each_with_index.select { |letra, index|
   # ...
}

一些例子可能有助于理解这一点。仅选择 奇数?<奇数? /code> 索引:

palavra_secreta_array.each_with_index.select { |letra, index|
   index.odd?
}
#=> [["r", 1], ["g", 3], ["a", 5], ["a", 7], ["o", 9]]

仅选择字母等于“ R” 或等于等于的元素“ o” :( || 表示“或”)

palavra_secreta_array.each_with_index.select { |letra, index|
   letra == "r" || letra == "o"
}
#=> [["r", 1], ["o", 2], ["r", 4], ["o", 9], ["r", 10]]

或合并,仅选择“ R” “ o” 和一个奇数索引:(&amp;&amp;&amp; 表示“ and”)

palavra_secreta_array.each_with_index.select { |letra, index|
  (letra == "r" || letra == "o") && index.odd?
}
#=> [["r", 1], ["o", 9]]

,您可以看到,使用块是一种非常灵活且强大的选择元素的方法。

回到你的问题。您当前的块仅检查 total_encontrado 是否更大或等于 1 。它不考虑当前字母或其索引。而且由于 total_encontrado 大于 1 ,因此block 始终返回 true 和<代码>选择返回所有元素。

要选择匹配通缉字母的字母 letra_procurada 的元素,您将使用:

palavra_secreta_array.each_with_index.select { |letra, index|
   letra == letra_procurada
}
#=> [["a", 5], ["a", 7]]

"letra_procurada" means "letter wanted", so you seem to be under the impression that you have to pass the element you're looking for to select like this:

letra_procurada = "a"

palavra_secreta_array.each_with_index.select { |letra_procurada, index| }
#                                               ^^^^^^^^^^^^^^^

However, this is not at all how block arguments or select in particular work. If you would replace letra_procurada by a string literal, you'd get a SyntaxError right-away:

palavra_secreta_array.each_with_index.select { |"a", index| }
# SyntaxError: unexpected string literal

A block contains code that the method you pass the block to (here: select) can invoke (multiple times, just once or not at all). Upon each block invocation, the block arguments (|letra_procurada, index|) are passed from the method (i.e. from select) into the block.

You call select, but select calls the block. This is also known as a "callback".

In your example, select invokes the block for each element and passes that element as the block arguments letra_procurada and index. It then expects the block to return either true or false. That return value determines whether or not that element will be included in the result.

Since the block's first argument can be any letter, you likely want a more general variable name. Something like this:

palavra_secreta_array.each_with_index.select { |letra, index|
   # ...
}

Some examples might help to understand this. To select only elements with an odd? index:

palavra_secreta_array.each_with_index.select { |letra, index|
   index.odd?
}
#=> [["r", 1], ["g", 3], ["a", 5], ["a", 7], ["o", 9]]

To select only elements whose letter is equal to "r" or equal to "o": (|| means "or")

palavra_secreta_array.each_with_index.select { |letra, index|
   letra == "r" || letra == "o"
}
#=> [["r", 1], ["o", 2], ["r", 4], ["o", 9], ["r", 10]]

Or combined, to select only elements with a letter of "r" or "o" and an odd index: (&& means "and")

palavra_secreta_array.each_with_index.select { |letra, index|
  (letra == "r" || letra == "o") && index.odd?
}
#=> [["r", 1], ["o", 9]]

As you can see, using a block is a very flexible and powerful way to select elements.

Back to your problem. Your current block just checks whether total_encontrado is larger or equal to 1. It doesn't take the current letter or its index into account. And because total_encontrado is larger than 1, the block always returns true and select returns all elements.

To select only elements whose letter match the wanted letter letra_procurada, you'd use:

palavra_secreta_array.each_with_index.select { |letra, index|
   letra == letra_procurada
}
#=> [["a", 5], ["a", 7]]
追风人 2025-02-19 09:56:16

当处理相应元素满足特定条件的集合或字符串索引的问题时,要返回特定条件时,使用一系列索引 [0,1,..,n]通常很方便。例如,如果一个人想返回数字 arr = [3,2,6,5,4] 的元素的索引数组,则可能会写下以下一个< sup> 1 :

arr.each_index.select  { |i| arr[i].odd? }
(0..arr.size-1).select { |i| arr[i].odd? }
arr.size.times.select  { |i| arr[i].odd? }

所有返回 [0,3]

对于涉及字符串的当前问题,我们可以使用上面的最后两种方法中的任何一种:

(0..palavra_secreta.size-1).select { |i| palavra_secreta[i] == letra_procurada }
palavra_secreta.size.times.select { |i| palavra_secreta[i] == letra_procurada }

两者都返回 [5,7]

我相信这种方法读得很好,因为读者应该立即明显地返回一系列索引。

1。我意识到,在#2中,我本可以写(0 ... arr.size),但是我发现混合两个和三点范围往往会产生错误,所以我只使用三个 - 当无法使用两个点范围时,请范围。

When dealing with problems where an array of indices of a collection or string whose corresponding elements satisfy a particular condition is to be returned, it is often convenient to work with an array of indices [0,1,..,n]. For example, if one wanted to return an array of indices of elements of the array arr = [3,2,6,5,4] that are odd numbers, one might write one of the following1:

arr.each_index.select  { |i| arr[i].odd? }
(0..arr.size-1).select { |i| arr[i].odd? }
arr.size.times.select  { |i| arr[i].odd? }

All return [0, 3].

For the present problem, involving a string, we could use either of the last two approaches above:

(0..palavra_secreta.size-1).select { |i| palavra_secreta[i] == letra_procurada }
palavra_secreta.size.times.select { |i| palavra_secreta[i] == letra_procurada }

Both return [5, 7].

I believe this approach reads well, as it should be immediately apparent to the reader that a selection of indices is being returned.

1. I realize that in #2 I could have written (0...arr.size), but I have found that mixing two- and three-dot ranges tends to spawn bugs, so I only use three-dot ranges when a two-dot range cannot be used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文