sofs1
sofs1

Reputation: 4176

How to check if each word in an array contains a substring and reject those in Ruby on Rails?

a = ["SUPER", "SOME_VALID", "ROME_INVALID", "SUPER_GOOD"]
a = a.reject { |x| x.in? ["GOOD", "VALID"]}
#=> ["SUPER", "SOME_VALID", "ROME_INVALID", "SUPER_GOOD"]

I don't want words that contain substring VALID or GOOD.

Output should be ["SUPER"] only.

Upvotes: 2

Views: 119

Answers (4)

Stefan
Stefan

Reputation: 114188

grep_v would work:

a = ["SUPER", "SOME_VALID", "ROME_INVALID", "SUPER_GOOD"]
a = a.grep_v(/GOOD|VALID/)
#=> ["SUPER"]

Upvotes: 4

Sebastián Palma
Sebastián Palma

Reputation: 33420

What in? does is to check if the receiver is present in the array passed as argument, meaning:

1.in?([1, 2]) # true
3.in?([1, 2]) # false

That's to say, it checks for the "whole" object, rather than a part of it.

If you want to reject the elements in your array that match with VALID and/or GOOD, you can use =~:

["SUPER", "SOME_VALID", "ROME_INVALID", "SUPER_GOOD"].reject { |word| word =~ /VALID|GOOD/ } # ["SUPER"]

Notice, this is also going to reject words like "VALIDITY", "GOODNESS", etc.

Upvotes: 3

Surya
Surya

Reputation: 16002

You could use include?:

a.reject { |x| ["GOOD", "VALID"].any?{ |word| x.include?(word) } }
#=> ["SUPER"]

Upvotes: 1

harpocrates
harpocrates

Reputation: 140

You could say this:

a = a.reject { |x| x.include?("GOOD") || x.include?("VALID")}

Upvotes: 3

Related Questions