【问题标题】:Hash merge and reorder哈希合并和重新排序
【发布时间】:2012-09-10 20:02:38
【问题描述】:

我希望合并 2 个哈希值并将其提供给我,如下面的“预期结果”部分所示。 有什么想法吗?

示例数据:

list1 = { '1' => [item1] }
list2 = { '1' => [item2], '2' => [item3]}

预期结果

{ 
  '1' => {:from_list1 => [item1], :from_list2 => [item2]},
  '2' => {:from_list2 => [item3]}
}

注意:这几乎是我在Best way to combine 2 hashes in this order中的另一个问题的更新

【问题讨论】:

  • 这个应该比较简单;到目前为止你尝试过什么?
  • 您的预期结果不是有效的 Ruby 对象。
  • 为什么不是有效的 ruby​​ 对象?这是一个哈希。并且散列的值也是散列。那是一个错误的红宝石对象吗? Ruby 毫无问题地接受了它。 item1、item2 等是我定义的某个类的对象。
  • @DivyaBhargov 不要说谎。在 rogal111 编辑问题之前,它不是散列。在 rogal111 编辑之前,Ruby 肯定不会接受它。

标签: ruby-on-rails ruby arrays hash


【解决方案1】:

尝试嵌套inject

list1={'1'=>['item1'],'3'=>['item4']}
list2={"1"=>["item2"], "2"=>["item3"]} 

list2.inject(list1.inject({}) { |c, (k, v)| 
   c[k]=(list2.has_key?(k) ? {:from_list1=>v,:from_list2=>list2[k]} : {:from_list1=>v}) 
   c
   }) { |c, (k, v)| 
      c[k]||={:from_list2=>v}
      c
}

#result:
{"1"=>{:from_list1=>["item1"], :from_list2=>["item2"]}, "3"=>{:from_list1=>["item4"]}, "2"=>{:from_list2=>["item3"]}} 

【讨论】:

  • 不..当列表之一没有密钥时,它不起作用。在上面的例子中,它只会返回 {"1"=>​​{:from_list1=>[item1], :from_list2=>[item2]}, "2"=>[item3]} 。看到第二个键有一个数组而不是哈希
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 2016-11-21
  • 2010-10-20
  • 2015-04-22
相关资源
最近更新 更多