You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用puts显示多项目?旅行应用订单输出格式优化求助

Fixing Order Item Display Format in Your Travel App

Hey there! I get exactly what you're aiming for—you want your order summary to show up in a clean, user-friendly way like 2 SevendaySurfSportTour instead of the raw hash output. Let's tweak your display method to make that happen.

The Issue

Right now, your display method uses puts @order_items, which outputs Ruby's default string representation of a hash (like {"SevendaySurfSportTour"=>2}). To get the format you want, we need to iterate over each item in the hash and format the output manually.

The Solution

Update your TourOrder class's display method to loop through each key-value pair in @order_items and print them in your desired format:

class TourOrder
  def initialize
    @order_items = Hash.new(0)
  end
  def add_item(name, quantity)
    @order_items[name] += quantity
  end
  def get_items
    return @order_items
  end
  def display
    puts "Thank you for coming!"
    # Iterate over each tour and its quantity
    @order_items.each do |tour_name, quantity|
      puts "#{quantity} #{tour_name}"
    end
  end
end

How It Works

  • @order_items.each do |tour_name, quantity| loops through every entry in your hash. For each entry, tour_name is the key (the tour's name) and quantity is the value (how many of that tour were ordered).
  • puts "#{quantity} #{tour_name}" uses string interpolation to combine the quantity and tour name in the exact format you want.

Example Output

If you run this code:

order = TourOrder.new
order.add_item("SevendaySurfSportTour", 2)
order.display

You'll get this clean output:

Thank you for coming!
2 SevendaySurfSportTour

This also works if you have multiple tour types in the order—each one will get its own properly formatted line.

内容的提问来源于stack exchange,提问作者Devbreaker29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:06:50