作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
10, "b" => 20, "c"=>34, "d"=>3} h2 = { "a" => 11, "b" => 21, -6ren">
我一直在尝试在 Ruby 中组合两个散列。例如:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
我想要的输出是:
h{"a"=> 10, 11, "b"=>20,21, "c"=> 34, "d"=>3,15}
每个散列都有相同的键,除了第二个散列可能会丢失一些。我希望这两个值然后由相同的键表示。
这是我不成功的代码:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
h3= h1.update(h2){|key1, key2, val1, val2 |key1,h2_val=h2}
它给出:
{"a"=>{"a"=>11, "b"=>21, "d"=>15}, "b"=>{"a"=>11, "b"=>21, "d"=>15}, "c"=>34, "d"=>{"a"=>11, "b"=>21, "d"=>15}}
我只是 Ruby 的新手,所以我想我在这里遗漏了一些非常基本的东西。我将不胜感激任何帮助。
最佳答案
关于:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
p h1.merge(h2){|key, old, new| Array(old).push(new) } #=> {"a"=>[10, 11], "b"=>[20, 21], "c"=>34, "d"=>[3, 15]}
这就是我将如何编写它来组合 2 个以上的哈希值:
h1 = { "a" => 10, "b" => 20, "c"=>34, "d"=>3}
h2 = { "a" => 11, "b" => 21, "d"=>15}
h3 = { "a" => 11, "b" => 21, "c"=> 1, "d"=>15}
merge_to_array = -> x,y { x.merge(y){|key, old, new| Array(old).push(new)} }
p [h1,h2,h3].reduce &merge_to_array #=> {"a"=>[10, 11, 11], "b"=>[20, 21, 21], "c"=>[34, 1], "d"=>[3, 15, 15]}
关于ruby - 将两个散列与一个公共(public) key 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21573316/
我是一名优秀的程序员,十分优秀!