如何在Ruby中使用带有块的索引或rindex?

时间:2009-11-10 08:56:14

标签: ruby arrays enumerable

是否有任何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

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

5 个答案:

答案 0 :(得分:7)

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

但这很简洁:

(0..ar.size-1).select { |i| ar[i] > 4 }
编辑:应该提到这是Ruby 1.8.6。

另一个编辑:忘了三点,它可以保存一个完整的角色,以及清理-1,我感到不舒服:

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

答案 1 :(得分:3)

据我所知,这只是红宝石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? }

答案 2 :(得分:1)

让爆炸注入方法的力量!!! ; - )

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合作)

答案 3 :(得分:1)

不,但如果你愿意,你可以随时修补它:

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]                                                        

答案 4 :(得分:0)

基本上是迈克伍德豪斯的答案重新格式化,以消除丑陋的范围。

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

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

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