Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ruby on rails - How to add up the number representations of the objects of the hashes in an array of hashes?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...