现在,我正在合并这样的两个哈希:
department_hash = self.parse_department html
super_saver_hash = self.parse_super_saver html
final_hash = department_hash.merge(super_saver_hash)
输出:
{:department => {“Pet Supplies”=> {“Birds”=> 16281,“Cats”=> 245512, “Dogs”=> 513926,“Fish& Aquatic Pets”=> 46811,“Horses”=> 14805, “昆虫”=> 364,“爬行动物和两栖动物”=> 5816,“小 动物“=> 19769}},:super_saver => {”免费超级保护 送货“=> 126649}}
但是现在我想在未来合并更多。例如:
department_hash = self.parse_department html
super_saver_hash = self.parse_super_saver html
categories_hash = self.parse_categories html
如何合并多个哈希?
答案 0 :(得分:25)
怎么样:
[department_hash, super_saver_hash, categories_hash].reduce &:merge
答案 1 :(得分:16)
您可以再次致电merge
:
h1 = {foo: :bar}
h2 = {baz: :qux}
h3 = {quux: :garply}
h1.merge(h2).merge(h3)
#=> {:foo=>:bar, :baz=>:qux, :quux=>:garply}
答案 2 :(得分:9)
您可以使用Enumerable#inject
h = {}
arr = [{:a=>"b"},{"c" => 2},{:a=>4,"c"=>"Hi"}]
arr.inject(h,:update)
# => {:a=>4, "c"=>"Hi"}
arr.inject(:update)
# => {:a=>4, "c"=>"Hi"}
答案 3 :(得分:0)
在完成本问题及其答案之后,我花了一些时间来弄清楚如何合并多嵌套哈希。事实证明,我正在不正确地迭代哈希集合,导致null
值出现各种问题。
此sample命令行应用程序显示了如何将多个哈希值与store
和merge!
的组合合并,具体取决于它们是否为顶级哈希键。它使用带有一些已知密钥名称的命令行参数进行分类。
Gist URL中的完整代码在下面提供为礼貌:
# Ruby - A nested hash example
# Load each pair of args on the command-line as a key-value pair
# For example from CMD.exe:
# call ruby.exe ruby_nested_hash_example.rb Age 30 Name Mary Fav_Hobby Ataraxia Fav_Number 42
# Output would be:
# {
# "data_info": {
# "types": {
# "nums": {
# "Age": 30,
# "Fav_Number": 42
# },
# "strings": {
# "Name": "Mary",
# "Fav_Hobby": "Ataraxia"
# }
# },
# "data_id": "13435436457"
# }
# }
if (ARGV.count % 2 != 0) || (ARGV.count < 2)
STDERR.puts "You must provide an even amount of command-line args to make key-value pairs.\n"
abort
end
require 'json'
cmd_hashes = {}
nums = {}
strings = {}
types = {}
#FYI `tl` == top-level
all_tl_keys = {}
data_info = {}
data_id = {:data_id => "13435436457"}
_key = ""
_value = ""
element = 0
ARGV.each do |i|
if element % 2 == 0
_key=i
else
if (i.to_i!=0) && (i!=0)
_value=i.to_i
else
_value=i
end
end
if (_key != "") && (_value != "")
cmd_hashes.store(_key, _value)
_key = ""
_value = ""
end
element+=1
end
cmd_hashes.each do |key, value|
if value.is_a? Numeric
nums.store(key, value)
else
strings.store(key, value)
end
end
if nums.size > 0; types.merge!(:nums => nums) end
if strings.size > 0; types.merge!(:strings => strings) end
if types.size > 0; all_tl_keys.merge!(:types => types) end
if data_id.size > 0; all_tl_keys.merge!(data_id) end
if all_tl_keys.size > 0; data_info.merge!(:data_info => all_tl_keys) end
if data_info.size > 0; puts JSON.pretty_generate(data_info) end
答案 4 :(得分:0)
假设你有arr = [{x: 10},{y: 20},{z: 30}]
然后做
arr.reduce(:merge)