javascript - Nested Loop in Ruby, Hash and Array -
how can in ruby
var pcodeprice = { 'gr1': 3.11, 'sr1': 5, 'cf1': 11.23 }; var basket = ['gr1', 'sr1', 'gr1', 'gr1', 'cf1']; var total = []; (i = 0, x = basket.length; < x; i++) { (var prop in pcodeprice) { if (basket[i] == prop) { total.push(pcodeprice[prop]) } } }
this loops through array , checks see if item matches key of hash in inner loop, if pushes value new array.
i cant 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]
Comments
Post a Comment