我有以下数组:
array = [{"email"=>"test@test.com", "name"=>"Test"},
{"email"=>"testA@test.com", "name"=>"Test A"},
{"name"=>"Test B", "email"=>"testB@test.com"},
{"email"=>"testC@test.com", "name"=>"Test C"},
{"name"=>"Test D", "email"=>"testD@test.com"},
{"email"=>"testE@test.com"},
{"name"=>"Test F", "email"=>"testF@test.com"}]
我有一个“黑名单”电子邮件列表,例如:
blacklist = ["testC@test.com"]
我想做这样的事情:
array - blacklist
# => should remove element {"email"=>"testC@test.com", "name"=>"Test C"}
肯定有一种性感的Ruby方式可以用.select或者其他东西来做这件事,但是我还没弄清楚。我试过这个无济于事:
array.select {|k,v| v != "testC@test.com"} # => returns array without any changes
答案 0 :(得分: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阻塞单个元素,并且在这种情况下该元素将是Hash,如果|k,v|
有两个元素数组作为元素,array
技巧将起作用
答案 1 :(得分:2)
怎么样
array.delete_if {|key, value| value == "testC@test.com" }