Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Remove element from array of hashes

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
like image 679
MorningHacker Avatar asked Oct 22 '11 02:10

MorningHacker


2 Answers

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.

like image 50
mu is too short Avatar answered Nov 15 '22 00:11

mu is too short


How about

array.delete_if {|key, value| value == "[email protected]" } 
like image 40
Alexander Pogrebnyak Avatar answered Nov 15 '22 00:11

Alexander Pogrebnyak