-1

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!

mechnicov
  • 12,025
  • 4
  • 33
  • 56

1 Answers1

5

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]] }
mechnicov
  • 12,025
  • 4
  • 33
  • 56