我无法在哈希中找到与鞋子尺码相关的最大值。这是我到目前为止所拥有的
def biggest_shoe
max_size = nil
game_hash.each do |location, team_data|
team_data[:players].each do |player, stats|
size = stats[:shoe]
if max_size < size
max_size = size
#binding.pry
end
end
end
end
我能够使用stats [:shoe]在整个迭代过程中成功地获取鞋子的单个值,但是从那以后,我还没有找到从哈希值迭代中提取最大尺寸的方法。
哈希:
def game_hash
{
home: {
:team_name => "Brooklyn Nets",
:colors => ["Black", "White"],
:players => {
"Alan Anderson" => {
:number => 0,
:shoe => 16,
:points => 22,
:rebounds => 12,
:assists => 12,
:steals => 3,
:blocks => 1,
:slam_dunks => 1
},
"Reggie Evans" => {
:number => 30,
:shoe => 14,
:points => 12,
:rebounds => 12,
:assists => 12,
:steals => 12,
:blocks => 12,
:slam_dunks => 7
},
"Brook Lopez" => {
:number => 11,
:shoe => 17,
:points => 17,
:rebounds => 19,
:assists => 10,
:steals => 3,
:blocks => 1,
:slam_dunks => 15
},
"Mason Plumlee" => {
:number => 1,
:shoe => 19,
:points => 26,
:rebounds => 12,
:assists => 6,
:steals => 3,
:blocks => 8,
:slam_dunks => 5
},
"Jason Terry" => {
:number => 31,
:shoe => 15,
:points => 19,
:rebounds => 2,
:assists => 2,
:steals => 4,
:blocks => 11,
:slam_dunks => 1
}
}
},
away: {
:team_name => "Charlotte Hornets",
:colors => ["Turquoise", "Purple"],
:players => {
"Jeff Adrien" => {
:number => 4,
:shoe => 18,
:points => 10,
:rebounds => 1,
:assists => 1,
:steals => 2,
:blocks => 7,
:slam_dunks => 2,
},
"Bismak Biyombo" => {
:number => 0,
:shoe => 16,
:points => 12,
:rebounds => 4,
:assists => 7,
:steals => 7,
:blocks => 15,
:slam_dunks => 10
},
"DeSagna Diop" => {
:number => 2,
:shoe => 14,
:points => 24,
:rebounds => 12,
:assists => 12,
:steals => 4,
:blocks => 5,
:slam_dunks => 5
},
"Ben Gordon" => {
:number => 8,
:shoe => 15,
:points => 33,
:rebounds => 3,
:assists => 2,
:steals => 1,
:blocks => 1,
:slam_dunks => 0
},
"Brendan Haywood" => {
:number => 33,
:shoe => 15,
:points => 6,
:rebounds => 12,
:assists => 12,
:steals => 22,
:blocks => 5,
:slam_dunks => 12
}
}
}
}
end
答案 0 :(得分:2)
像许多常见的事物一样,Ruby有一个用于此的工具:
game_hash.values.map do |team_data|
team_data[:players]
end.values.map do |stats|
stats[:shoe]
end.max
答案 1 :(得分:0)
这只内衬将所有鞋子的价值都整理成一个数组,然后选择最大值。
game_hash.map { |_, v| v[:players].map { |_, v| v[:shoe] } }.flatten.max
创建一种方法来获取所选键的最大值
def pick_max_stat_from(h, key)
h.map { |_, v| v[:players].map { |_, v| v[key] } }.flatten.max
end
pick_max_stat_from game_hash, :slam_dunks # => 15
也许这对于按位置获取最大值可能有用:
game_hash.transform_values { |v| v[:players].map { |_, v| v[:shoe] }.max }
# = {:home=>19, :away=>18}
答案 2 :(得分:0)
game_hash[:home][:players].max_by { |_name, stats| stats[:shoe] }.last[:shoe]
#=> 19