Here's another shot at her, with a spray of bltxd and Hsuu responding, and hopefully retains as much of the spirit of the original grep as possible (even if it is verbose):
module Enumerable def grepv(condition) if block_given? each do |item| yield item if not condition === item end else inject([]) do |memo, item| memo << item if not condition === item memo end end end end
If you put a block, then everything will be lazy, as you expected. If you do not supply a block, there is a small duplicate of the code. I really want Andrew Grimm to answer in the general case.
>> (%w(1 2 3) + [4]).cycle(3).grepv(Fixnum) => ["1", "2", "3", "1", "2", "3", "1", "2", "3"] >> (%w(1 2 3) + [4]).cycle(3).grepv(/[12]/) => ["3", 4, "3", 4, "3", 4]
In any case, you do not pay up to O(n^2) for comparing the elements, as in the worst case, if you subtract the subtraction of the array.
jdsumsion
source share