Alex Rivera | Logout

Ruby equivalent to grep -v

Asked 2010-11-12T15:08:39.347
9

This is what I've been doing instead:

my_array.reject { |elem| elem =~ /regex/ }.each { ... }

I feel like this is a little unwieldy, but I haven't found anything built in that would let me change it to my_array.grepv /regex/ { ... }

Is there such a function?

Edit
Report

2 Answers

7

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.

answered 2010-11-17T23:02:56.943
3

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/) { ... }
answered 2010-11-12T16:18:02.090

Your Answer