Suppose a regex comes from calling code, outside of the current context, and then is passed on to another call implemented outside of the current project:
["1", "2"].grep(/1/) #=> ["1"]
Is there a simple, Rubyish way to achieve the following behavior when the call is being made?
["1", "2"].grep(/1/.negate) #=> ["2"]
This behavior is similar to switching the =~
operator with the !~
operator. It is possible to use #select
or #reject
, of course, or to open up or subclass Regexp
. But I'm curious whether there is a way already available in Ruby to negate the matches returned by a regular expression in the manner above. Also, I don't care whether false
or nil
or true
or the position of a match are involved in accomplishing this effect.
There is a theoretical question which is relevant but which goes beyond the simple considerations here.
EDIT: I get that iterators are the general way to go in Ruby for filtering a list, but people are overlooking the constraints of the question. Also, I think there is something nicely functional about the way the regex is being inverted. I don't see it as being overwrought or too-clever by half; it's plain-old object-oriented programming and the kind of thing that Ruby excels at doing.
["1", "2"].reject { |e| /1/ === e }
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