mydata = {:data => [
{
:first_name = > "abc",
:foo_id = > "21sd",
:roll = > 43
},
{:first_name = > "def",
:foo_id = > "2uf",
:roll = > 81
},
{:first_name = > "xyz",
:foo_id = > "ac32",
:roll = > 2
}
]
}
在mydata中:roll有某种方式损坏了值
我有一个已排序的哈希,其数据为:foo_id => :roll
sorted = {"21sd" => 7, "ac32" => 89, "2uf" => 92}
(即通过排序的正确值:roll)
我想使用这个'排序'哈希重新排列'mydata',并且使用'sorted'hash中的正确值覆盖'mydata'中:roll
的值。所以最后'mydata'看起来像
mydata = {:data => [
{
:first_name = > "abc",
:foo_id = > "21sd",
:roll = > 7
},
{:first_name = > "xyz",
:foo_id = > "ac32",
:roll = > 89
},
{:first_name = > "def",
:foo_id = > "2uf",
:roll = > 92
}
]
}
UPADTE::roll在排序
中可能不是唯一的考虑mydata可能有100,000个哈希
我使用'sorted'的嵌套循环实现了结果,并且在每次迭代中,从'mydata'搜索foo_id并更正值并在新变量中对排序数据进行处理。这很难看。
correct = []
sorted.each {|k, v|
mydata[:data].each {|h| # hate looping here
if h[:foo_id] == k # hate searching here, if i have 100,000 record in 'mydata'
h[:roll] = v
correct << h
end
}
}
mydata = {:data => correct}
如果mydata包含大量数据集,则这不是最佳解决方案。有人建议一些最佳解决方案吗?
答案 0 :(得分:2)
这应该有用......
mydata[:data].each do |h|
h[:roll] = sorted[h[:foo_id]]
end
没有办法避免循环通过mydata [:data],因为它是一个数组...但你不需要把东西塞进一个新的变量......只需更新你已经得到的东西。
除非我不理解这个问题......
编辑:我没有拿起排序权。新解决方案:mydata[:data].each do |h|
h[:roll] = sorted[h[:foo_id]]
end
mydata[:data].sort_by!{|h| h[:roll]}
答案 1 :(得分:0)
data = [
{
:first_name => "abc",
:foo_id => "21sd",
:roll => 7
},
{:first_name => "xyz",
:foo_id => "ac32",
:roll => 89
},
{:first_name => "def",
:foo_id => "2uf",
:roll => 92
}
]
sorted = {"21sd" => 7, "ac32" => 89, "2uf" => 92}
foo_id_name = data.map do |rec|
{ rec[:foo_id] => rec[:first_name] }
end.reduce(&:merge)
new_data = sorted.map do |foo_id, new_roll|
{
:first_name => foo_id_name[foo_id],
:foo_id => foo_id,
:roll => new_roll
}
end
puts new_data.inspect #=> [{:first_name=>"abc", :foo_id=>"21sd", :roll=>7}, {:first_name=>"xyz", :foo_id=>"ac32", :roll=>89}, {:first_name=>"def", :foo_id=>"2uf", :roll=>92}]