我有这种形式的SQL结果:
Id Amount1 Amount2 Amount3
1 10 10 12
2 20 13 14
3 30 15 15
我正在尝试将Id存储在Key中,将所有其他值存储在值
中类似的东西:
{1=>{:Amount1=>"10", :Amount2=>"10", :Amount3=>"12"}, 2=>{:Amount1=>"20", :Amount2=>"13", :Amount3=>"14"}}
这是我目前所拥有的:
hashn = Hash.new
sqlresult.each { |x|
hashn[x['PPS_Id']] = x['Gift_Card_Amount1']
hashn[x['PPS_Id']] = x['Gift_Card_Amount2']
hashn[x['PPS_Id']] = x['Gift_Card_Amount3']
}
我相信这会覆盖以前的价值,请你帮忙。
答案 0 :(得分:1)
您也可以将数组分配给哈希键
像下面的东西
hashn= {}
sqlresult.each { |x|
hashn[x['PPS_Id']] = [] unless hashn[x['PPS_Id']]
hashn[x['PPS_Id']] << x['Gift_Card_Amount1']
hashn[x['PPS_Id']] << x['Gift_Card_Amount2']
hashn[x['PPS_Id']] << x['Gift_Card_Amount3']
}
答案 1 :(得分:0)
假设您的Sql Result是一个活动记录集合,这应该有效:
required_hash = {}
sqlresult.each do |obj|
required_hash[obj.id] =
{ amount1: obj.amount1, amount2: obj.amount2, amount3: obj.amount3 }
end
required_hash