获取 Ruby 个满足特定条件的索引数组

Getting Ruby array of indexes which fulfill a certain condition

问题:我有一个数组。我对那些满足特定条件的数组元素感兴趣。我不想要一个由这些数组元素组成的新数组,而是一个由这些元素的索引组成的数组。

玩具示例:

a=[3,4,8,9,11,14]

我想要一个所有奇数元素的索引数组,即 [0, 3, 4]

我想到了以下两个解决方案,我都不太喜欢:

(1)

a.each_index.select {|i| a[i].odd? }

(2)

a.each_with_index.select { |el, i| el.odd? }.map(&:last)

我不喜欢变体 (1),因为 a 的重复需要 a 合理地应该是一个变量(而不是任意表达式)

我不喜欢变体(2),因为each_with_index构造了一个由值和索引组成的小数组(对)数组,虽然我最后只需要索引部分。

基本上,我更喜欢方法 (2)。有没有大佬有什么办法,怎么写更简洁?

如果您使用的是 Ruby 版本 >= 2.7,您可以使用 filter_map 方法,如下所示:

a = [3,4,8,9,11,14]

a.each_with_index.filter_map {|n, i| i if n.odd?}

输入

a = [3, 4, 8, 9, 11, 14]

代码

p a.filter_map { |value| a.index(value) if value.odd? }