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?
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
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.
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.
What about inverting the regex?
["ab", "ac", "bd"].grep(/^[^a]/) # => ["bd"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With