[英]Convert Array to Hash in ruby with following structure
我有一个以下数组,显示用户的信息和一些与用户相关的值。 以下数组包含两个用户Akiyo Riggs和Bingo的信息
a1 = [["Akiyo Riggs", -32, "OverTime Hours", "",12],["Akiyo Riggs", -32,
"Regular Hours", "", 18],["Bingo",-12,"OverTime Hours","",14], ["Bingo",
-12,"Regular Hours","",32]]
如何转换为以下哈希数组,其中键是用户名,值是具有相应值的哈希值
[{"Akiyo Riggs"=>{"OverTime Hours"=>["", 12], "Regular Hours"=>["", 18]},
{"Bingo"=>{"OverTime Hours"=>["", 14], "Regular Hours"=>["", 32]}]
a1.map { |x,_,p,*ps| {x => {p => ps} } }.reduce({}, :deep_merge)
# => {"Akiyo Riggs"=>{"OverTime Hours"=>["", 12], "Regular Hours"=>["", 18]},
# "Bingo"=>{"OverTime Hours"=>["", 14], "Regular Hours"=>["", 32]}}
注意:如果考虑效率,请考虑使用deep_merge!
而不是deep_merge
,因此reduce
不会在每次迭代时创建新的哈希。
一些解释:
a1.map { |x,_,p,*ps| {x => {p => ps} } }
给了我们一系列像这样的哈希
[{"Akiyo Riggs"=>{"OverTime Hours"=>["", 12]}},
{"Akiyo Riggs"=>{"Regular Hours"=>["", 18]}},
{"Bingo"=>{"OverTime Hours"=>["", 14]}},
{"Bingo"=>{"Regular Hours"=>["", 32]}}]
我们可以递归地与ActiveSupport Hash#deep_merge合并
你可以做这样的事情(但是,这不是你想要的完全):
res = a1.group_by {|x| x[0] }.reduce({}) {|h, x| h[ x[0] ] = x[1].reduce({}) {|hh, xx| hh[ xx[2] ] = xx[3..-1] ; hh } ; h }
# => {"Akiyo Riggs"=>{"OverTime Hours"=>["", 12], "Regular Hours"=>["", 18]}, "Bingo"=>{"OverTime Hours"=>["", 14], "Regular Hours"=>["", 32]}}
确切的事情是做额外的步骤:
res.keys.map {|k| {k => res[k]}}
# => [{"Akiyo Riggs"=>{"OverTime Hours"=>["", 12], "Regular Hours"=>["", 18]}}, {"Bingo"=>{"OverTime Hours"=>["", 14], "Regular Hours"=>["", 32]}}]
a1.each_with_object({}) do |array, result|
result[array[0]] ||= {}
result[array[0]].merge!(array[2] => [array[3], array[4]])
end.map { |k, v| { k => v } }
# => [{"Akiyo Riggs"=>{"OverTime Hours"=>["", 12], "Regular Hours"=>["", 18]}}, {"Bingo"=>{"OverTime Hours"=>["", 14], "Regular Hours"=>["", 32]}}]
array.each_with_object({}) do |(name, _, hours_type, a, b), hash|
hash[name] ||= {}
hash[name][hours_type] = [a, b]
end.map do |name, values_hash|
{name => values_hash}
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.