如何计算数组中对象的平均值?

Nob*_*ita 8 ruby average

假设我有一个这样的数组:

[
  {
    "player_id"         => 1,
    "number_of_matches" => 2,
    "goals"             => 5
  },
  {
    "player_id"         => 2,
    "number_of_matches" => 4,
    "goals"             => 10
  }
]
Run Code Online (Sandbox Code Playgroud)

我想在所有球员中获得每场比赛的平均进球数,而不是每个球员的平均进球数,而是总平均数.

我想到.each并且存储每个单独的平均值,最后将它们全部加起来并除以我拥有的玩家数量.但是,我正在寻找一种Ruby /单行方式.

tok*_*and 17

根据要求,单行:

avg = xs.map { |x| x["goals"].to_f / x["number_of_matches"] }.reduce(:+) / xs.size
Run Code Online (Sandbox Code Playgroud)

一个更具可读性的片段:

goals, matches = xs.map { |x| [x["goals"], x["number_of_matches"]] }.transpose 
avg = goals.reduce(:+).to_f / matches.reduce(:+) if goals
Run Code Online (Sandbox Code Playgroud)

  • @Kyle:用分号替换每个换行符.Voilà:单线. (2认同)