Rails Haml - 按索引加入哈希值

时间:2016-01-01 21:43:59

标签: ruby-on-rails hash

- @nutritions = Hash.new
    - @ingredients.each_with_index do |ingredient,i|
      - ingredient.nutritions.each_with_index do |nutrition, j|
        - @nutritions[[i,j]] = nutrition.amount
    - @nutritions.each do |nutrition|
      = nutrition

给了我两个"块"含量(例如含有2种成分,含有4种营养素):

[[ingredient, nutrition], amount]

[[0, 0], 900.0]
[[0, 1], 3769.0]
[[0, 2], 0.0]
[[0, 3], 100.0] 

[[1, 0], 258.0]
[[1, 1], 1080.0]
[[1, 2], 64.0]
[[1, 3], 0.0] 

我正在寻找一种方法来添加每个哈希值(金额), 并将其存储在后面的另一个键中,如

[[2, 0], 1158.0]
[[2, 1], 4849.0]
[[2, 2], 64.0]
[[2, 3], 100.0] 

因此。如果有5种成分,将它们的总和存储在第6块"块"

解决方案: (感谢Smathy!)

[[0, 0], 900.0]
[[3, 0], 1507.0]
[[0, 1], 3769.0]
[[3, 1], 6310.0]
[[0, 2], 0.0]
[[3, 2], 136.0]
[[0, 3], 100.0]
[[3, 3], 101.0] 

[[1, 0], 258.0]
[[1, 1], 1080.0]
[[1, 2], 64.0]
[[1, 3], 0.0] 

[[2, 0], 349.0]
[[2, 1], 1461.0]
[[2, 2], 72.0]
[[2, 3], 1.0] 

1 个答案:

答案 0 :(得分:1)

直截了当地告诉你:

- @nutritions = Hash.new
- end_of_list = @ingredients.length
- @ingredients.each_with_index do |ingredient,i|
  - ingredient.nutritions.each_with_index do |nutrition, j|
    - @nutritions[[i,j]] = nutrition.amount
    - @nutritions[[end_of_list,j]] ||= 0
    - @nutritions[[end_of_list,j]] += nutrition.amount

可能有更好的方法来实现你的真正目标,但是如果不知道你实际上想要实现什么,就无法猜出最好的方法。