Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rubyish way to invert a regular expression

Tags:

regex

ruby

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.

like image 778
Eric Walker Avatar asked Dec 07 '22 06:12

Eric Walker


1 Answers

["1", "2"].reject { |e| /1/ === e }
like image 50
Boris Stitnicky Avatar answered Dec 21 '22 03:12

Boris Stitnicky