[英]Rails: Remove element from array of hashes
I have the following array: 我有以下数组:
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"}]
I have a list of "blacklist" emails, for instance: 我有一个“黑名单”电子邮件列表,例如:
blacklist = ["testC@test.com"]
I want to do something like this: 我想做这样的事情:
array - blacklist
# => should remove element {"email"=>"testC@test.com", "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. 当然有一种性感的Ruby方式可以用.select或者其他东西来做这件事,但是我还没弄清楚。 I tried this to no avail:
我试过这个无济于事:
array.select {|k,v| v != "testC@test.com"} # => returns array without any changes
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): 或者如果你想使用
select
而不是reject
(也许你不想伤害任何人的感受):
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|
尝试将无法工作,因为数组移动Enumerable阻止单个元素,并且在这种情况下该元素将是哈希,
|k,v|
trick would work if array
had two element arrays as elements though. 如果
array
有两个元素数组作为元素,那么技巧会起作用。
怎么样
array.delete_if {|key, value| value == "testC@test.com" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.