【问题标题】:Create a hash containing arrays创建包含数组的哈希
【发布时间】:2016-01-27 19:20:09
【问题描述】:

我正在尝试创建一个名为winners 的哈希。

我有一个名为arcade 的模型,每个模型甚至都有与之关联的games。我正在尝试创建与每个奖项匹配的获胜者哈希。

arcade.rb 是:

def prizes_by winner
  winners = {}
  self.games.each do |g|
   high_score = g.high_score
   if high_score
     winners[high_score.user] ||= []
     winners[high_score.user] << g
   end
  end
end 

当我取回哈希时,它不包含每个 high_score.user 的密钥。

我希望哈希看起来像:

winners{
   user1 => [game1, game2, game3...]
   user2 => [game 4]
   user3 => [game10, game11]
   ...
}

【问题讨论】:

  • winner参数有什么用?
  • @WandMaker 我刚刚修复它应该是 high_score
  • 你期望什么哈希,例如?
  • @sschmeck 我在问题的底部提供了这一点
  • 哈希实际上包含什么?这看起来应该可以工作

标签: ruby-on-rails ruby hashmap


【解决方案1】:

这样的事情怎么样?使用each_with_object

def prizes_by winner
  games.each_with_object({}) do |game, hash|
    if high_score = game.high_score
      (hash[high_score.user] ||= []).push(game)
    end
  end
end

我还没有测试过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 2017-04-28
    • 1970-01-01
    • 2011-04-20
    • 2013-04-30
    • 2017-04-13
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多