【问题标题】:How can I use index or rindex with a block in Ruby?如何在 Ruby 中将 index 或 rindex 与块一起使用?
【发布时间】:2010-12-14 22:58:47
【问题描述】:

是否有任何内置的 Array 或 Enumerable 允许我使用块搜索元素并返回其索引?

类似于:

ar = [15,2,33,4,50,69]
indexes = ar.find_indexes {|item| item > 4 == 0}
# indexes will now contain 0,2,4,5

添加我自己的很容易,但我想知道这是否已经存在?

【问题讨论】:

    标签: ruby arrays enumerable


    【解决方案1】:

    我认为没有任何内置功能,至少我没有注意到 ArrayEnumerable 文档中以前未检测到的任何内容。

    不过,这很简洁:

    (0..ar.size-1).select { |i| ar[i] > 4 }
    

    编辑:应该提到这是 Ruby 1.8.6。

    另一个编辑:忘记了三点,它可以保存整个字符,以及清理 -1,我对此感到不舒服:

    (0...ar.size).select { |i| ar[i] > 4 }
    

    【讨论】:

      【解决方案2】:

      我知道这只是 ruby​​ 1.9

      indexes = ar.collect.with_index { |elem, index| index if elem > 4 }.
                   select { |elem| not elem.nil? }
      

      编辑:对于 ruby​​ 1.8 试试

      require 'enumerator'
      indexes = ar.to_enum(:each_with_index).
                   collect { |elem, index| index if elem > 4 }.
                   select { |elem| not elem.nil? }
      

      【讨论】:

      • xs.select { |elem| not elem.nil? } -> xs.compact
      【解决方案3】:

      就让注入法的威力爆炸吧!!! ;-)

      ar.inject([]){|a,i| a.empty? ? a << [0, i] : a << [a.last[0]+1,i]}
        .select{|a| a[1] > 4}
        .map{|a| a[0]}
      

      (适用于 ruby​​ 1.8.6)

      【讨论】:

      • 这个调试起来应该很愉快。
      • 当然,但幸运的是不需要调试 ;)
      • 从来没有。直到有:)
      【解决方案4】:

      不,但如果你愿意,你可以随时对其进行修补:

      class Array
        def find_indexes(&block)
          (0..size-1).select { |i| block.call(self[i]) }
        end
      end
      
      ar = [15,2,33,4,50,69]
      p ar.find_indexes {|item| item > 4 }  #=> [0, 2, 4, 5]                                                        
      

      【讨论】:

      • 是的,我知道这是一个选项,但我认为可能已经存在类似的东西。
      【解决方案5】:

      基本上是 Mike Woodhouse 的答案重新格式化以删除丑陋的范围。

      ar.each_index.select{|item| item > 4}
      

      这是适用于 Ruby 1.8.7 的 johnanthonyboyd 答案的一个版本

      ar.enum_with_index.each.select{|item| item.first > 4}.map(&:last)
      

      【讨论】:

      • 看不到 each_index 的工作原理——它必须返回一个 Enumerable,不是吗? enum_with_index 看起来很有用,但应该注意它仅适用于 1.8.7 及更高版本,方便的 map(&:...) 东西(在 Rails 之外)也是如此。此外,文档建议它需要require enumerator。我还在1.8.6,所以无法查看。
      • Each 和 each_index 和其他迭代器方法返回它迭代的 Enumerable 对象。至于另一个的语法,它在我本地的 irb 安装中工作(使用 ruby​​ 1.8.7,我没有意识到这是最近添加的)
      • 我猜你的意思是:ar.each_index.select { |idx| ar[idx] &gt; 4}
      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 2019-10-06
      相关资源
      最近更新 更多