【问题标题】:Rails: Remove element from array of hashesRails:从哈希数组中删除元素
【发布时间】:2011-12-13 00:13:25
【问题描述】:

我有以下数组:

 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

【问题讨论】:

    标签: ruby-on-rails ruby arrays hash


    【解决方案1】:

    我想你正在寻找这个:

    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,但如果 array 有两个元素数组作为元素,|k,v| 技巧将起作用。

    【讨论】:

    • 太棒了!感谢您的快速周转 :) 实际上,您回答得如此之快,以至于我什至无法“接受” SO 系统上的答案。
    • 还有一个排除函数是!include的别名
    • @Darren:唯一的缺点是exclude? 是Rails 扩展,这会导致双重负面领域:) 我可能会选择reject/include?。跨度>
    【解决方案2】:

    怎么样

    array.delete_if {|key, value| value == "testC@test.com" } 
    

    【讨论】:

    • 类似@mu太短的select,应该是array.delete_if {|hash| hash["email"] == "testC@test.com"}
    • delete_if 就地工作(通常不是一个好主意),OP 似乎想要一个新数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2015-11-13
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多