Ruby-on-rails Rails:从哈希数组中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7857019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:13:05  来源:igfitidea点击:

Rails: Remove element from array of hashes

ruby-on-railsrubyarrayshash

提问by MorningHacker

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:

当然,使用 .select 或其他东西有一种性感的 Ruby 方式来做到这一点,但我一直无法弄清楚。我试过这个无济于事:

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

回答by mu is too short

I think you're looking for this:

我想你正在寻找这个:

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

or if you want to use selectinstead 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|trick would work if arrayhad two element arrays as elements though.

尝试将不起作用,因为数组将 Enumerable 块传递给单个元素,并且在这种情况下该元素将是 Hash,|k,v|如果array有两个元素数组作为元素,该技巧将起作用。

回答by Alexander Pogrebnyak

How about

怎么样

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