试图找出一种从哈希散列中获取最大/最小值的方法。例如,我希望得到死亡率最高的玩家和杀死率最高的玩家。
哈希示例:
{ 1234 =>
{ :steamID => 1234,
:alias => "Bob",
:kills => "50",
:deaths => "10"
},
5678 =>
{ :steamID => 5678,
:alias => "Jim",
:kills => "10",
:deaths => "12"
},
}
尝试输出类似的内容:
{ :most_kills =>
{ :steamID => 12345,
:name => "Bob",
:stat => "50"},
:most_deaths =>
{ :steamID => 12345,
:name => "Bob",
:stat => "50"
}
}
答案 0 :(得分:0)
以下内容将找到具有最大杀死和死亡统计数据的玩家,并将输出映射到所需格式:
input = { 1234 =>
{ steamID: 1234,
alias: "Bob",
kills: "50",
deaths: "10"
},
5678 =>
{ steamID: 5678,
alias: "Jim",
kills: "10",
deaths: "12"
},
}
output = [:kills, :deaths].each_with_object({}) do |stat, h|
max = input.max_by {|k,v| v[stat]}
h["most_#{stat}".to_sym] = {
:steamID => max[0],
:name => max[1][:alias],
:stat => max[1][stat]
}
end
输出结果为:
{
:most_kills => {
:steamID => 1234,
:name => "Bob",
:stat => "50"
},
:most_deaths => {
:steamID => 5678,
:name => "Jim",
:stat => "12"
}
}
答案 1 :(得分:0)
我可能这样写:
def most(input, key_name)
_, v = input.max_by { |_,v| v[key_name.to_sym] }
[("most_#{key_name}").to_sym, v]
end
["deaths", "kills"].map {|key_name| most(input, key_name) }.to_h
#=> {:most_deaths=>{:steamID=>5678, :alias=>"Jim",
# :kills=>"10", :deaths=>"12"},
# :most_kills =>{:steamID=>1234, :alias=>"Bob",
# :kills=>"50", :deaths=>"10"}}