繁体   English   中英

选择方法等效于仅在Ruby中保留索引

[英]select method equivalent to retain indices only in Ruby

假设我在Ruby中有以下数组:

a=[1,2,3]

而且我只想要大于2的元素的索引,而不是元素本身。 是否有一个Array方法将等效于:

d=[]
a.each_with_index{ |x, i| d.push(i) if x > 2 }

就像是:

a.select_index{ | x | x > 2 }

谢谢。

你可以做 :

a = [1,2,3]
a.each_index.select { |i| a[i] > 2 }
# => [2]
> a = [1, 2,3]
=> [1, 2, 3]
> a.map { |n| a.index(n) if n > 2 }.compact
=> [2]

还不如短奥雅纳和Elle的答案,但下面是指a只有一次。

a.to_enum.with_index.select{|x, _| x > 2}.map(&:last)
# => [2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM