如何将两个不同散列数组的值一起添加?

时间:2010-12-07 22:57:56

标签: ruby arrays hash

我有两个哈希数组。哈希的关键是不同的:

player_scores1 = [{:first_name=>"Bruce", :score => 43, :time => 50},
                  {:first_name=>"Clark", :score => 45, :minutes => 20}]

player_scores2 = [{:last_name=>"Wayne", :points => 13, :time => 40},
                  {:last_name=>"Kent", :points => 3, :minutes => 20}]

我想创建一个新的哈希数组,它们加起来:得分和:一起指向并将其分配给一个名为:score的键。我还想组合:first_name和:last_name并将其分配给名为:full_name的键。我想丢弃任何其他钥匙。

这会产生这个数组:

all_players = [{:full_name => "Bruce Wayne", :score => 56}, 
               {:full_name => "Clark Kent", :score => 48}]

有优雅的方法吗?

4 个答案:

答案 0 :(得分:8)

这样的事情:

player_scores1.zip(player_scores2).map { |a,b|
    {
        :full_name => a[:first_name]+' '+b[:last_name],
        :score => a[:score]+b[:points]
    }
}

答案 1 :(得分:0)

您正在寻找的代码是:

final = []
player_scores1.each_index do |index|
  entry_1 = player_scores1.values(index)
  entry_2 = player_scores2.values(index)[:first_name]
  score = entry_1[:score] + entry_2[:points]
  final << {:full_name => "#{entry_1[:first_name]} #{entry_2[:last_name]}", :score => score }
end

任何有关收紧这项建议的建议都会非常感激!

答案 2 :(得分:0)

这很有效。如果那还不够优雅,我不会这样做。

player_scores1 = [{:first_name=>"Bruce", :score => 43, :time => 50},
                  {:first_name=>"Clark", :score => 45, :minutes => 20}]

player_scores2 = [{:last_name=>"Wayne", :points => 13, :time => 40},
                  {:last_name=>"Kent", :points => 3, :minutes => 20}]

p (0...[player_scores1.length, player_scores2.length].min).map {|i| {
    :full_name => player_scores1[i][:first_name] + " " + player_scores2[i][:last_name], 
    :score => player_scores1[i][:score] + player_scores2[i][:points]
}}

此示例位于Codepad

答案 3 :(得分:0)

这使用zip一个块来循环哈希,加入名称并总结:

all_players = []
player_scores1.zip(player_scores2) { |a, b| 
  all_players << { 
    :full_name => a[:first_name] + ' ' + b[:last_name],
    :score     => a[:score] + b[:points]
  } 
}
all_players # => [{:full_name=>"Bruce Wayne", :score=>56}, {:full_name=>"Clark Kent", :score=>48}]