Ruby - 使用索引进行过滤的函数式方法

Dom*_*mra 5 ruby functional-programming

我有一个像这样的数组:

stuff = ["A", " ", "C", " ", "E", " ", "G"]
Run Code Online (Sandbox Code Playgroud)

我想返回一个包含所有索引的数组,其中数据是空格。例如:

[1, 3, 5]
Run Code Online (Sandbox Code Playgroud)

有没有一种很好的功能性方法来做到这一点?我知道有一个each_with_index方法返回 an Enumerable,但我不知道如何使用过滤器来使用它。

编辑:NVM,经过 30 分钟的尝试才解决了它。这是我的方法。

indexes = stuff.collect.with_index { |elem, index| index if elem == " "}.
             select { |elem| not elem.nil? }
Run Code Online (Sandbox Code Playgroud)

Ja͢*_*͢ck 6

多年后,Ruby 2.7 的发布Enumerable#filter_map()使这一切变得更简单:

stuff.filter_map.with_index { |elem, index| index if elem == ' ' }
Run Code Online (Sandbox Code Playgroud)


Ste*_*nev 4

让我为您缩短一下:

['A', ' ', 'C', ' ', 'E', ' ', 'G'].map.with_index { |e, i| i if e == ' ' }.compact
Run Code Online (Sandbox Code Playgroud)

问题是您可以使用Enumerable#compact而不是执行select. 另外,我发现#map这是一个更流行的术语,特别是当你谈论函数式编程时,但最终还是苹果和橙子。