我需要一个类似于Array#select
的函数,但是不仅传递数据项的块,而且传递元素的索引(类似于Enumerable#each_with_index
)。我尝试这样做:Ruby:组合枚举器,制作一个新的枚举器
class Array
def select_with_index
self.each_with_index.select {|*args| yield(*args)}.map(&:first)
end
end
这似乎确实工作:如预期在
["a", "a"]
['a','b','a','a','c'].select_with_index {|letter,index| letter == 'a' && index > 1 }
结果。然而,我不喜欢我的解决方案是,那个有提供一个块。 Ruby内核中的类似方法可以在没有块的情况下调用并生成Enumerator
。我怎样才能做到这一点?我知道我可以使用block_given?
来测试块的存在,但我该如何继续?我需要Fiber
吗?
顺便说一句,代码应该与Ruby 1.9.3兼容。和2.x.
它很难在元编程, G。 in kinda'public_send selector_name,&λ'。 – mudasobwa
那么,给这个名字吧:http://pastie.org/10786273 –