9
You know how Symbol#to_proc helps with chaining? You can do the same with regular expressions:
class Regexp
def to_proc
Proc.new {|string| string =~ self}
end
end
["Ruby", "perl", "Perl", "PERL"].reject(&/perl/i)
=> ["Ruby"]
But you probably shouldn't. Grep doesn't just work with regular expressions - you can use it like the following
[1,2, "three", 4].grep(Fixnum)
and if you wanted to grep -v that, you'd have to implement Class#to_proc, which sounds wrong.
I don't believe there's anything built-in like this, but it's simple enough to add:
class Array
def grepv(regex, &block)
self.reject { |elem| elem =~ regex }.each(&block)
end
end
Note that you need to use parens around the regex when you call this function, otherwise you get a syntax error:
myarray.grepv(/regex/) { ... }