我正在尝试解决Ruby Monk Primer" Orders and Costs"问题。 https://rubymonk.com/learning/books/1-ruby-primer/problems/155-restaurant
我设计了一个解决方案,只有在一个订单通过时才有效,但不是多个订单。
我很难理解我的代码在功能上与建议的答案有何不同。我也不明白Ruby Monk如何传递"多个订单"。 Inject和.each之间的任何澄清都会非常有用。
class Restaurant
def initialize(menu)
@menu = menu
end
def cost(*orders)
orders.inject(0) do | total_cost, order |
order.each { | item, qt | total_cost = total_cost + @menu[item] * qt }
return total_cost
end
end
end
与Ruby Monk的代码相比:
def cost(*orders)
orders.inject(0) do |total_cost, order|
total_cost + order.keys.inject(0) {|cost, key| cost + @menu[key]*order[key] }
感谢您的帮助:)
答案 0 :(得分:0)
使用每个实现的实现实际上很好。问题是通过显式返回total_cost,您将提前退出该函数。 Ruby会隐式返回要评估的最后一件事,所以删除“return”这个词,你的解决方案就可以了!