我正在尝试解决这个非常基本的挑战。在我开始添加订单的总利润之前,其他所有方法都运行良好,并且收到错误消息:“ challange3.rb:64:in <main>': undefined method
+'for nil:NilClass(NoMethodError)”。
您正在一家酒吧里工作,那里有当前积压的饮料:
3杯鸡尾酒, 2水和 6杯啤酒 编写一个程序询问客户的订单。
如果他们订购鸡尾酒,则在需要制作的鸡尾酒数量上加一个。 如果他们订购了水,则在需要添加的水数量上加一。 如果他们订购啤酒,则在倒入的啤酒数量中加一。 打印最终的饮料订单,以便您知道该怎么做。 鸡尾酒的售价为22美元,制作成本为8美元。 啤酒的售价为12美元,倒出的价格为3美元。 水的售价为6美元,制造成本为0.15美元。 打印出您的订单的总利润。
这是我的代码
backlog_cocktails = 3
backlog_waters = 2
backlog_beers = 6
cocktail_cost = 8
water_cost = 0.15
beer_cost = 3
cocktail_selling_price = 22
water_selling_price = 6
beer_selling_price = 12
total_profit = " "
p "Are you ordering?"
are_you_ordering = gets.chomp
while are_you_ordering == "yes"
puts "We have Cocktails, Waters and beers for order."
puts "What orders do you want to make?"
customer_order = gets.chomp
if customer_order == "cocktail"
backlog_cocktails += 1
cocktail_profit = (cocktail_selling_price - cocktail_cost) * backlog_cocktails
elsif customer_order == "water"
backlog_waters += 1
water_profit = (water_selling_price - water_cost) * backlog_waters
else customer_order == "beer"
backlog_beers += 1
beer_profit = (beer_selling_price - beer_cost) * backlog_beers
end
p "We got cocktail: #{backlog_cocktails}, water: #{backlog_waters} and beer: #{backlog_beers} to make."
puts "Do you want to make more order?"
are_you_ordering = gets.chomp
total_ profit = cocktail_profit + water_profit + beer_profit
p total_profit
end
答案 0 :(得分:2)
之所以发生此错误,是因为您在计算nil
时试图将其添加到当前total_profit
的变量中。要解决此错误,请在cocktail_profit
循环之前将water_profit
,beer_profit
和while
初始化为0。
cocktail_profit = 0.0
water_profit = 0.0
beer_profit = 0.0
while are_you_ordering == "yes"
...