'Percentage in array of hashes?

I have hash and an array of hashes array:

hash = {"BEGIN"=>5, "END"=>10}


array = [
    {:name=>"aaa", :phase=>"END", :quantity=>6},
    {:name=>"bbb", :phase=>"END", :quantity=>4},
    {:name=>"ccc", :phase=>"BEGIN", :quantity=>5}
  ]

How can I calculate the percentage on the array of hashes taking the value from hash and get this result?

[
  {:name=>"aaa", :phase=>"END", :quantity=>60%},
  {:name=>"bbb", :phase=>"END", :quantity=>40%},
  {:name=>"ccc", :phase=>"BEGIN", :quantity=>100%}
]

Thank you in advance!



Solution 1:[1]

To get percents as integers

hash = { "BEGIN" => 5, "END" => 10 }

array = [
  { name: "aaa", phase: "END", quantity: 6 },
  { name: "bbb", phase: "END", quantity: 4 },
  { name: "ccc", phase: "BEGIN", quantity: 5 }
]

array.map! { |el| el.merge(quantity: el[:quantity] * 100 / hash[el[:phase]]) }

p array
# will print
# [{:name=>"aaa", :phase=>"END", :quantity=>60}, {:name=>"bbb", :phase=>"END", :quantity=>40}, {:name=>"ccc", :phase=>"BEGIN", :quantity=>100}]

or you using each

array.each { |el| el[:quantity] = el[:quantity] * 100 / hash[el[:phase]] }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mechnicov