深度嵌套哈希中相同键的值求和

时间:2019-03-22 17:33:47

标签: ruby

我以前可能已经发布了此嵌套哈希。每个父键(:home,:away)的哈希由4个级别组成。我想访问每个父键的第4级,以便将所有:points值加在一起,然后我想比较每个求和的值并找出哪个是最大的值。我自己尝试过此操作,但是出现

错误
  

没有将符号隐式转换为整数(repl):136:在winning_team'的parser = argparse.ArgumentParser(description="Description for my parser") parser.add_argument("-v", "--velocity", action="store", required=True, help="The velocity of the object is required") parser.add_argument("-a", "--angle", action="store", type=float, required=True, help="The angle of the object is required") parser.add_argument("-h", "--height", required=False, default= 1.2, help="The height of the object is not required. Default is set to 1.2 meters" ) 块中(repl):135:在[]' (repl):136:in winning_team'(repl):158:in`'' / p>

下面是哈希和我对这段代码的尝试,对为什么会出现此错误的任何解释以及对获得所需输出的任何改进都将非常有帮助。如果太混乱了,我深表歉意。

each'
  (repl):135:in

2 个答案:

答案 0 :(得分:1)

game_hash[:home][:players].sum { |_, h| h[:points] }
#⇒  96

:away相同。

答案 1 :(得分:0)

如果您正在寻找获胜的团队,可以将Enumerable#max_byEnumerable#sum一起使用。

winning_team = game_hash.values.max_by do |team|
  team[:players].sum { |_, h| h[:points] }
end

puts winning_team[:team_name]

或者,您可以使用Hashie::MashOpenStruct之类的东西来将哈希表变成更友好的对象,并使用如下访问器方法:

require 'hashie/mash'
game = Hashie::Mash.new(game_hash)

winning_team = [game.home, game.away].max_by do |team|
  team.players.values.sum(&:points)
end

puts winning_team.team_name
相关问题