Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop elements from array if regexp does not match

Tags:

arrays

regex

ruby

Is there a way to do this?

I have an array:

["file_1.jar", "file_2.jar","file_3.pom"]

And I want to keep only "file_3.pom", what I want to do is something like this:

array.drop_while{|f| /.pom/.match(f)}

But This way I keep everything in array but "file_3.pom" is there a way to do something like "not_match"?

I found these:

f !~ /.pom/ # => leaves all elements in array

OR

f !~ /*.pom/ # => leaves all elements in array

But none of those returns what I expect.

like image 266
Jakub Zak Avatar asked Apr 14 '15 11:04

Jakub Zak


2 Answers

How about select?

selected = array.select { |f| /.pom/.match(f) }
p selected
# => ["file_3.pom"]

Hope that helps!

like image 181
Paweł Dawczak Avatar answered Oct 08 '22 05:10

Paweł Dawczak


In your case you can use the Enumerable#grep method to get an array of the elements that matches a pattern:

["file_1.jar", "file_2.jar", "file_3.pom"].grep(/\.pom\z/)
# => ["file_3.pom"]

As you can see I've also slightly modified your regular expression to actually match only strings that ends with .pom:

  • \. matches a literal dot, without the \ it matches any character
  • \z anchor the pattern to the end of the string, without it the pattern would match .pom everywhere in the string.

Since you are searching for a literal string you can also avoid regular expression altogether, for example using the methods String#end_with? and Array#select:

["file_1.jar", "file_2.jar", "file_3.pom"].select { |s| s.end_with?('.pom') }
# => ["file_3.pom"]
like image 36
toro2k Avatar answered Oct 08 '22 05:10

toro2k