Ruby Hash内在的另一个Hash是空的

时间:2015-06-02 18:17:21

标签: ruby hash

我创建了一个方法,用于在Hash中对每个用户的所有提交进行分组:

def calculate_month_ranking(commits)
  rank = Hash.new(Hash.new(0))  
  commits.each do |commit_yml|
    commit = YAML.load commit_yml.data

    commit[:commits].each do |local_commit|      
      time = Time.parse(local_commit[:timestamp])
      month = "#{time.month}/#{time.year}"
      rank[month][commit[:user_name]]+= 1
      binding.pry # for debug
    end

  end

  rank  
end

但只有rank[month]有值,如果我只调用rank,则值为空。为什么?

[1] pry(main)> rank[month]
=> {"user1"=>4, "user2"=>1}
[2] pry(main)> rank
=> {}

1 个答案:

答案 0 :(得分:0)

你的问题在于流线,分配不正确到哈希

      rank[month][commit[:user_name]]+= 1

我不知道你的价值观,所以我在这里添加一个你可以尝试的例子

将哈希声明为以下

rank = {}  

将值指定为密钥对

rank.merge!(:month => {:user_name => 'test' })

听我添加控制台输出

2.0.0-p481 :007 > rank = {}  
=> {} 
2.0.0-p481 :008 > rank.merge!(:month => {:user_name => 'test' })
=> {:month=>{:user_name=>"test"}} 
2.0.0-p481 :009 > rank
=> {:month=>{:user_name=>"test"}} 
2.0.0-p481 :010 > rank[:month]
=>  {:user_name=>"test"}