Rails:从哈希数组中删除元素

问题描述 投票:23回答:2

我有以下数组:

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

我有一个“黑名单”电子邮件列表,例如:

 blacklist = ["[email protected]"]

我想做这样的事情:

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

当然有一种性感的Ruby方式可以用.select或者其他东西来做这件事,但是我还没弄清楚。我试过这个无济于事:

 array.select {|k,v| v != "[email protected]"} # => returns array without any changes
ruby-on-rails ruby arrays hash
2个回答
51
投票

我想你正在寻找这个:

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

或者如果你想使用select而不是reject(也许你不想伤害任何人的感受):

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

您的

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

尝试将无法工作,因为数组移动Enumerable阻止单个元素,在这种情况下该元素将是哈希,如果|k,v|有两个元素数组作为元素,array技巧将起作用。


2
投票

怎么样

array.delete_if {|key, value| value == "[email protected]" } 
© www.soinside.com 2019 - 2024. All rights reserved.