如何使用puts显示多项目?旅行应用订单输出格式优化求助
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_nameis the key (the tour's name) andquantityis 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

