减少Ruby中的多个变量

时间:2012-03-23 05:17:50

标签: ruby reduce enumerable

AFAIK在减少数组时我们只能输出一次变量,如下所示:

(0..10).reduce(0) do |sum, value|
  sum + value
end

如果我有一个哈希对象数组,我可以减少数组并输出多个变量,如:

({:grade => 100, :sex => 'female'}, {:grade => 90, :sex => 'male'}).reduce(0, 0, 0) do |sum_of_grades, sum_of_male, sum_of_female, value|
  sum_of_grades = sum_of_grades + value[:grade]
  sum_of_male += 1 if value[:sex] == 'male'
  sum_of_female +=1 if value[:sex] == 'female
end

1 个答案:

答案 0 :(得分:7)

在散列或任何其他合适的对象中聚合多个结果:

a.reduce({:sum_of_grades => 0, :sum_of_male => 0, :sum_of_female => 0}) do |result, value|
     result[:sum_of_grades] += value[:grade]
     result[:sum_of_male] += 1 if value[:sex] == 'male'
     result[:sum_of_female] += 1 if value[:sex] == 'female'
     result
end