7

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.

2
  • 1
    Are you aware that the . in /.pom/ matches any character? Commented Apr 14, 2015 at 11:22
  • BTW, where does your array come from? Commented Apr 14, 2015 at 11:28

3 Answers 3

9

How about select?

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

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

5

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"]

Comments

3

If you whant to keep only Strings witch responds on regexp so you can use Ruby method keep_if. But this methods "destroy" 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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.