2012-07-16 26 views
2

过滤我有一个这样的数组:红宝石 - 功能性的方式与指数

stuff = ["A", " ", "C", " ", "E", " ", "G"] 

和我要回所有的索引数组,其中的数据是一片空白说。例如:

[1, 3, 5] 

是否有一个很好的功能方法来做到这一点?我知道有一个each_with_index方法返回Enumerable,但我无法弄清楚如何使用过滤器。

编辑:NVM,JUST在30分钟的尝试后解决它。这是我的方法。

indexes = stuff.collect.with_index { |elem, index| index if elem == " "}. 
      select { |elem| not elem.nil? } 
+2

你也可以使用最后的.compact选择 – nurettin 2012-07-16 08:33:15

+0

搜索归档中的“红宝石列表内涵”,因为这是你需要什么(至少,如何模仿它们)。 – tokland 2012-07-16 08:49:46

回答

3

让我缩短了一点给你:

['A', ' ', 'C', ' ', 'E', ' ', 'G'].map.with_index { |e, i| i if e == ' ' }.compact 

的事情是,你可以使用Enumerable#compact,而不是做一个select的。另外,我发现#map是更受欢迎的术语,特别是当您谈论函数式编程时,最后是苹果和桔子。

+1

这种模式(最接近Ruby的列表理解)非常常见,facet有它的抽象:'map_select'。其他人称其为“comprehend”,其他人称为“compact_map”,... – tokland 2012-07-16 08:48:19

1

如果你使用它在多个地方,我会扩展Array类用这种方法

class Array 
    def index_all(val = nil) 
    ary = [] 
    each_with_index { |x, i| 
     ary.push(i) if x == val or block_given? && yield(x) 
    } 
    ary 
    end 
end 

['A', ' ', 'C', ' ', 'E', ' ', 'G'].index_all(" ") #=> [1, 3, 5]