1

我想用红宝石转换

[[1, 1], [2, 3], [3, 5], [4, 1], [1, 2], [2, 3], [3, 5], [4, 1]]

进入

[{1=>1}, {2=>3}, {3=>5}, {4=>1}, {1=>2}, {2=>3}, {3=>5}, {4=>1}]

在此之后获得所有不同键的总和:

{1=>3,2=>6,3=>10,4=>2}
4

4 回答 4

2

功能方法:

xs = [[1, 1], [2, 3], [3, 5], [4, 1], [1, 2], [2, 3], [3, 5], [4, 1]]    
Hash[xs.group_by(&:first).map do |k, pairs| 
  [k, pairs.map { |x, y| y }.inject(:+)]
end]
#=> {1=>3, 2=>6, 3=>10, 4=>2}

由于抽象( 的变体)和(+ ),使用Facets要简单得多:map_bygroup_bymashmapHash

require 'facets'
xs.map_by { |k, v| [k, v] }.mash { |k, vs| [k, vs.inject(:+)] }
#=> {1=>3, 2=>6, 3=>10, 4=>2}
于 2012-09-06T12:35:55.000 回答
2

对于第二个问题

sum = Hash.new(0)
original_array.each{|x, y| sum[x] += y}
sum # => {1 => 3, 2 => 6, 3 => 10, 4 => 2}
于 2012-09-06T12:37:40.593 回答
1

您不需要中间形式。

arrays = [[1, 1], [2, 3], [3, 5], [4, 1], [1, 2], [2, 3], [3, 5], [4, 1]]

aggregate = arrays.each_with_object Hash.new do |(key, value), hash|
  hash[key] = hash.fetch(key, 0) + value
end

aggregate # => {1=>3, 2=>6, 3=>10, 4=>2}
于 2012-09-06T12:29:10.587 回答
0
arr= [[1, 1], [2, 3], [3, 5], [4, 1], [1, 2], [2, 3], [3, 5], [4, 1]]

final = Hash.new(0)

second_step = arr.inject([]) do |arr,inner|
   arr << Hash[*inner]
   final[inner.first] += inner.last
   arr
end

second_step
#=> [{1=>1}, {2=>3}, {3=>5}, {4=>1}, {1=>2}, {2=>3}, {3=>5}, {4=>1}] 
final
#=> {1=>3, 2=>6, 3=>10, 4=>2}

如果你直接只需要最后一步

arr.inject(Hash.new(0)){|hash,inner| hash[inner.first] += inner.last;hash}
=> {1=>3, 2=>6, 3=>10, 4=>2} 
于 2012-09-06T13:03:39.133 回答