我有一个数组
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]
I am using 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]
关于ruby:数组中所有元素的索引小于给定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21385268/