2015-04-06 71 views
-1

我正在處理'訂單和成本'https://rubymonk.com/learning/books/1-ruby-primer/problems/155-restaurant的問題。問題說明是:以下教程中如何使用相同的按鍵將菜單項與訂購商品價格相關聯?

餐廳有傳入的訂單,您需要根據菜單計算出 的成本。

你可能有時

還有就是鍛鍊低於溶液(見解決方案)獲得多個訂單,看起來像這樣:

class Restaurant 
    def initialize(menu) 
    @menu = menu 
    end 

    def cost(*orders) 
    orders.inject(0) do |total_cost, order| 
     total_cost + order.keys.inject(0) {|cost, key| cost + @menu[key]*order[key] } 
    end 
    end 
end 

我不明白整個算法:我認爲是這樣 - 在def cost(*orders)total_cost是訂單成本。 key是項目,在這種情況下:米飯和麪條,但什麼是@menu[key]*order[key]的含義,我無法猜測。

任何人都可以解釋我這個練習嗎?

回答

1

如果

​​

所以

@menu['rice'] == 3.00 
order['rice'] == 1 
3.00 * 1 == 3 

@menu['beans'] == 2.50 
order['beans'] == 2 
2.50 * 2 == 5.00 

因此訂單總額8.00

key只是被傳遞到每個哈希查找的關鍵。這兩個散列order@menu都使用密鑰rice,其中一個涉及rice它在菜單上的價格,另一個涉及rice項目中的數量。

0

正如練習告訴你的,訂單是{:rice => 1,:noodles => 1}和{:rice => 2,:noodles => 2},菜單是{:rice => 3,: noodles => 2}

@menu[key]*order[key]只是將每個@menu與給定的鍵相乘,並且其順序與鍵相同。

@menu [:稻] *訂單[:稻]因此,對於所述第一奧德(:稻)

@menu[:rice] # => 3 multiplied with 3 (once from the first order, twice from the second) 

相同爲:麪條

@menu[:noodles] # => 2 multiplied with 3 (once from the first order, twice from the second) 

結果然後在9:大米和6用於:麪條=> total_costs = 15+

相關問題