How can i do this in Ruby
var pCodePrice = { 'GR1': 3.11, 'SR1': 5, 'CF1': 11.23 }; var basket = ['GR1', 'SR1', 'GR1', 'GR1', 'CF1']; var total = []; for (i = 0, x = basket.length; i < x; i++) { for (var prop in pCodePrice) { if (basket[i] == prop) { total.push(pCodePrice[prop]) } } }
This loops through the array and checks to see if the item matches the key of the hash in the inner loop, if so it pushes the value into a new array.
I just cant get it in Ruby,
Thanks
It's pretty simple in ruby using map.
pCodePrice = { 'GR1' => 3.11, 'SR1' => 5, 'CF1' => 11.23 }
=> {"GR1"=>3.11, "SR1"=>5, "CF1"=>11.23}
basket = ['GR1','SR1','GR1','GR1','CF1']
=> ["GR1", "SR1", "GR1", "GR1", "CF1"]
total = basket.map { |code| pCodePrice[code] }
=> [3.11, 5, 3.11, 3.11, 11.23]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.