我想合并一个嵌套的哈希.
a = {:book=>
[{:title=>"Hamlet",
:author=>"William Shakespeare"
}]}
b = {:book=>
[{:title=>"Pride and Prejudice",
:author=>"Jane Austen"
}]}
Run Code Online (Sandbox Code Playgroud)
我想合并是:
{:book=>
[{:title=>"Hamlet",
:author=>"William Shakespeare"},
{:title=>"Pride and Prejudice",
:author=>"Jane Austen"}]}
Run Code Online (Sandbox Code Playgroud)
实现这个目标的巢方法是什么?
我有一个哈希,我正在尝试为它提取键和值.散列具有嵌套散列和/或散列数组.
在检查了这个网站和几个样本后,我得到了关键和值.但是如果它的一系列哈希值很难提取.
例:
{
:key1 => 'value1',
:key2 => 'value2',
:key3 => {
:key4 => [{:key4_1 => 'value4_1', :key4_2 => 'value4_2'}],
:key5 => 'value5'
},
:key6 => {
:key7 => [1,2,3],
:key8 => {
:key9 => 'value9'
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我在下面的代码中如何循环遍历ruby中的哈希散列并迭代Ruby中深度嵌套的哈希值
def ihash(h)
h.each_pair do |k,v|
if v.is_a?(Hash) || v.is_a?(Array)
puts "key: #{k} recursing..."
ihash(v)
else
# MODIFY HERE! Look for what you want to find in the hash here
puts "key: #{k} value: #{v}"
end
end …
Run Code Online (Sandbox Code Playgroud) 我有两个哈希,其结构与此类似:
hash_a = { :a => { :b => { :c => "d" } } }
hash_b = { :a => { :b => { :x => "y" } } }
Run Code Online (Sandbox Code Playgroud)
我想将这些合并在一起以产生以下哈希:
{ :a => { :b => { :c => "d", :x => "y" } } }
Run Code Online (Sandbox Code Playgroud)
merge函数将在第一个哈希值中替换:a的值,其值为:第二个哈希值中的a.所以,我编写了自己的递归合并函数,如下所示:
def recursive_merge( merge_from, merge_to )
merged_hash = merge_to
first_key = merge_from.keys[0]
if merge_to.has_key?(first_key)
merged_hash[first_key] = recursive_merge( merge_from[first_key], merge_to[first_key] )
else
merged_hash[first_key] = merge_from[first_key]
end
merged_hash
end
Run Code Online (Sandbox Code Playgroud)
但我得到一个运行时错误:can't add a new …