Ruby:阵列中所有元素的索引小于给定值



我有一个数组

a=[10,20,30,10,3,2,200]

我想找到具有小于21的元素的索引。我肯定可以在循环中这样做,但是我想知道是否有更好的衬里方法。就像我们在r。

中一样

使用Array#each_index

进行下面的操作
a = [10,20,30,10,3,2,200]
a.each_index.select { |i| a[i] < 21 }
# => [0, 1, 3, 4, 5]

我正在使用Ruby 1.8.5

然后做

a = [10,20,30,10,3,2,200]
a.size.times.select { |i| a[i] < 21 }
# => [0, 1, 3, 4, 5]

以下情况下还有一些其他选择,而straigtforward解决方案只是不会做的:

a = [10,20,30,10,3,2,200]
a.size.times.with_object([]) { |i,b| b << i if a[i] < 21 } # or a.each_index.with...
a.size.times.map { |i| a[i] < 21 ? i : nil }.compact # or a.each_index.with...
a.zip( Array(0...a.size) ).select { |e,_| e < 21 }.map(&:last)
a.reduce([[],0]) { |(b,i),e| [e < 21 ? b << i : b, i + 1] }.first
a.each_with_object([]) {|e,a| a << (e.to_i < 21 ? a.size : nil) }.compact
a.each_with_object([[],[]]) {|e,(g,b)|
  e < 21 ? g << (g.size + b.size) : b << nil }.first
(a.each_with_object([-1]) { |_,b| i = a[b.last+1..-1].index {
  |f| f < 21 }; b << b.last + 1 + i if i })[1..-1]
b = a.dup
a.each_with_object([]) { |e,c| i = b.index(e); c << i if e < 21; b[i] = nil }
b = (a + [nil])
a.each.with_object([]) { |_,c|
  c << (a.size - b.index(nil)) if b.first.to_i < 21; b.rotate! }
a.join(',').gsub(/(d+)/) { |e| (e.to_i < 21) ? $`.count(',') : nil } 
           .gsub(',,',',').split(',').map(&:to_i)
# All => [0, 1, 3, 4, 5] 

这应该可以解决问题,并且是线性的:

a.each_with_index.inject([]) {|indexes, pair| indexes << pair.last if pair.first < 21; indexes}  

Ruby通常不需要找到索引,为什么要尝试?

这应该在1.8中正常工作:

[10,20,30,10,3,2,200].each_with_index.select{|x,_|x<21}.map{|_,i|i}

最新更新