24

I have the following array:

 array = [{"email"=>"[email protected]", "name"=>"Test"},
          {"email"=>"[email protected]", "name"=>"Test A"},
          {"name"=>"Test B", "email"=>"[email protected]"},
          {"email"=>"[email protected]", "name"=>"Test C"},
          {"name"=>"Test D", "email"=>"[email protected]"},
          {"email"=>"[email protected]"},
          {"name"=>"Test F", "email"=>"[email protected]"}]

I have a list of "blacklist" emails, for instance:

 blacklist = ["[email protected]"]

I want to do something like this:

 array - blacklist 
 # => should remove element {"email"=>"[email protected]", "name"=>"Test C"} 

Surely there is a sexy-Ruby way to do this with .select or something, but I haven't been able to figure it out. I tried this to no avail:

 array.select {|k,v| v != "[email protected]"} # => returns array without any changes

2 Answers 2

54

I think you're looking for this:

filtered_array = array.reject { |h| blacklist.include? h['email'] }

or if you want to use select instead of reject (perhaps you don't want to hurt anyone's feelings):

filtered_array = array.select { |h| !blacklist.include? h['email'] }

Your

array.select {|k,v| ...

attempt won't work because array hands the Enumerable blocks a single element and that element will be a Hash in this case, the |k,v| trick would work if array had two element arrays as elements though.

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

3 Comments

brilliant! thanks for the quick turnaround :) in fact, you answered so quickly that I can't even "accept" the answer on SO's system.
there is also an exclude function that is and alias for !include
@Darren: The only downside is that exclude? is a Rails extension and that would lead into double negative territory :) I'd probably go with the reject/include?.
2

How about

array.delete_if {|key, value| value == "[email protected]" } 

2 Comments

similar to @mu is too short's select, it should be array.delete_if {|hash| hash["email"] == "[email protected]"}
delete_if works inplace (usually not a good idea), the OP seems to want a new array.

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.