【问题标题】:Finding indices of element in array ruby在数组 ruby​​ 中查找元素的索引
【发布时间】:2015-08-19 04:48:32
【问题描述】:

如何在 ruby​​ 中找到具有特定值的数组中所有元素的索引?
IE。如果你有一个数组 [2,3,52,2,4,1,2],有没有比使用循环更简单的方法来获取数组中所有 2 的索引?因此,如果我要寻找 2,答案将类似于 [0,3,6]。
答案在 Get index of array element faster than O(n) 如果我只想找到给定元素的一个实例,则给出解决方案。

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:

    试试这个,

    arr = [2,3,52,2,4,1,2]
        output = []
        arr.each_with_index do |v,i|
           if v == 2
             output << i
           end
        end
    
    puts output #=> [0, 3, 6]
    

    【讨论】:

    • 谢谢你。我得到了一个完美的缩短版本!
    【解决方案2】:
    a
    # => [2, 3, 52, 2, 4, 1, 2]
    b = []
    # => []
    a.each_with_index{|i, ind| b << ind if i == 2}
    # => [2, 3, 52, 2, 4, 1, 2] 
    

    【讨论】:

    • 这不会根据您的要求为您提供输出。 Luka 或 Rick 的答案可能正是您想要的。
    • 您检查过数组 b...吗?我忘了粘贴那个输出..你自己检查一次
    【解决方案3】:

    也许你可以用这个:

    a = [2, 3, 52, 2, 4, 1, 2]
    
    b = a.map.with_index{|k, i| i if k == 2}.compact
    b
    # => [0,3,6]
    

    或者如果您想修改变量,请修改版本。

    a = [2, 3, 52, 2, 4, 1, 2]
    a.map!.with_index{|k, i| i if k == 2}.compact!
    a
    # => [0,3,6]
    

    【讨论】:

    • 既然你正在构建的是b,为什么要使用map?您正在将 a 映射到您不使用的数组。 a.each_with_index不是更直接吗?
    • @CarySwoveland 我在这种情况下修改了地图的用法。你说得对,在这种情况下我使用它“不正确”。
    【解决方案4】:
    a.each_with_object([]).find_all {|i, index| i == 2}.map {|i, index| index }
    

    我觉得还是有捷径的。

    另一个选项可能是:

    a.each_with_object([]).with_index {|(i, result), index| result << index if i == 2 }
    

    【讨论】:

      【解决方案5】:
      a = [2,3,52,2,4,1,2]
      
      a.each_index.select { |i| a[i]== 2 }
        #=> [0, 3, 6] 
      

      【讨论】:

        猜你喜欢
        • 2018-12-29
        • 2014-11-15
        • 2011-02-05
        • 2016-06-09
        • 2013-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        相关资源
        最近更新 更多