Removing elements from an array if regexp does not match

Is there any way to do this?

I have an array:

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

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

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

But this way I save everything in an array, but is "file_3.pom" is there a way to do something like "not_match"?

I found them:

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

OR

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

But none of them returns what I expect.

+4
source share
3 answers

How about select?

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

Hope this helps!

+7
source

In your case, you can use the method Enumerable#grepto get an array of elements matching the pattern:

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

, , , .pom:

  • \. , \
  • \z , .pom .

, , , String#end_with? Array#select:

["file_1.jar", "file_2.jar", "file_3.pom"].select { |s| s.end_with?('.pom') }
# => ["file_3.pom"]
+4

If you want to save only strings, then the witch responds to the regular expression so that you can use the Ruby keep_if method. But these methods β€œdestroy” the main array.

a = ["file_1.jar", "file_2.jar","file_3.pom"]
a.keep_if{|file_name| /.pom/.match(file_name)}
p a
# => ["file_3.pom"]
+2
source

All Articles