Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent to grep -v

Tags:

regex

grep

ruby

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?

like image 282
Hsiu Avatar asked Nov 12 '10 15:11

Hsiu


4 Answers

Ruby 2.3 implements an Enumerable#grep_v method that is exactly what you're after.

https://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-grep_v

like image 71
PJSCopeland Avatar answered Nov 09 '22 16:11

PJSCopeland


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.

like image 41
Andrew Grimm Avatar answered Nov 09 '22 18:11

Andrew Grimm


How about this?

arr = ["abc", "def", "aaa", "def"]
arr - arr.grep(/a/)  #=> ["def", "def"]

I deliberately included a dup to make sure all of them are returned.

like image 42
Kelvin Avatar answered Nov 09 '22 18:11

Kelvin


What about inverting the regex?

["ab", "ac", "bd"].grep(/^[^a]/) # => ["bd"]
like image 4
Ahmed Al Hafoudh Avatar answered Nov 09 '22 18:11

Ahmed Al Hafoudh