【问题标题】:In Ruby, how do I return all the index value of elements in an array that have the same string values in them?在 Ruby 中,如何返回数组中具有相同字符串值的元素的所有索引值?
【发布时间】:2015-07-30 21:43:09
【问题描述】:

如何返回数组中具有相同字符串值的元素的所有索引值?

例如:

myarray=[tree, bean, bean, bunny, frog, bean, soup]   

如果我使用 myarray.index(bean) 搜索“bean”,它将返回 1。如果我使用 myarray.rindex(bean) 进行相同的搜索,它将返回 5。

我需要返回[1, 2, 5]myarray.{does this method exist?}(bean) 方法。

有什么建议吗?

【问题讨论】:

标签: arrays ruby string calabash


【解决方案1】:

您可以使用#each_with_index(创建一对字符串,索引),然后使用#map(遍历对,如果匹配,则返回索引,否则返回零)最后#compact(删除零值)数组。

myarray.each_with_index.map{|x,i| x == "bean"? i : nil}.compact

稍微简单一点的解决方案,在效率方面也更好的解决方案可能是#each_index

 myarray.each_index.select{|x| myarray[x] == "bean"}

顺便说一句。您应该将变量命名为 my_array,而不是 myarray

【讨论】:

  • 使用map时,不要在块中返回空值,然后使用compact。这是在浪费 CPU 和内存,尤其是对于大型阵列。您可以通过定义一个空数组然后使用 each 并附加到块内的数组然后访问该数组来完成相同的事情,除非它不会浪费 CPU 或内存。
  • 感谢 Tin Man 的建议,你完全正确
  • 我建议用select 代替map
【解决方案2】:

下面给出的简单易懂的解决方案

myarray = [:tree, :bean, :bean, :bunny, :frog, :bean, :soup]

result = []
search_for = :bean

myarray.each_with_index() { |element, index| result << index if element == search_for }

p result

输出

[1, 2, 5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多