Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

An array of hashes like

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

Also another hash:

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

How would someone replace all the sizes by their respective numbers and sum up those numbers?

The problem could be solved manually by replacing the numbers with the sizes like so:

 [{color: "red", size: 3},{color: "blue", size: 1},{color: purple, size: 2},{color: "pink", size: 1}]

Then adding them up the number representation of the sizes would output: 7

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Iterate over your first array, replace :size with the corrospoding size from the second array:

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.each do |x|
  x[:size] = sizes[x[:size].to_sym]
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...