如何使用inject或map遍历散列数组

时间:2014-04-27 17:31:06

标签: ruby

有一系列哈希像:

arr = [
  {color: "red", size: "large"},
  {color: "blue", size: "small"},
  {color: "purple", size: "medium"},
  {color: "pink", size: "small"}
]

和哈希:

sizes = {small: 1, medium: 2, large: 3, x_large: 4}

我想知道如何用各自的数字替换所有尺寸并将这些数字相加。我知道如何使用each执行此操作,如下所示:

arr.each do |x|
  x[:size] = sizes[x[:size].to_sym]
end

有人会如何使用injectmap

执行此操作

2 个答案:

答案 0 :(得分:2)

执行:

ar = [
       {color: "red", size: "large"}, {color: "blue", size: "small"},
       {color: 'purple', size: "medium"},{color: "pink", size: "small"}
     ]
hash = {small: 1, medium: 2, large: 3, x_large: 4}
ar.inject(0) { |sum,elem_hash| sum + hash[elem_hash[:size].to_sym] }
# => 7

答案 1 :(得分:2)

arr = [
  {color: "red", size: "large"},
  {color: "blue", size: "small"},
  {color: "purple", size: "medium"},
  {color: "pink", size: "small"}
]

sizes =   {small: 1, medium: 2, large: 3, x_large: 4}

arr.map { |x| x[:size] = sizes[x[:size].to_sym] }.inject(:+)
# => 7
arr
# => [{:color=>"red", :size=>3}, {:color=>"blue", :size=>1}, 
# =>  {:color=>"purple", :size=>2}, {:color=>"pink", :size=>1}]