如何在Ruby旅行费用程序中存储多组用户旅行相关输入?
Hey there! Nice progress on your trip cost calculator. The key here is to use an array of hashes—this lets you store each trip's details as a structured set of key-value pairs, and keep all those trips in a single collection you can easily access later.
First, let's fix a small bug in your current code: you're converting the trip location to an integer with to_i, but locations are strings (like "Paris" or "Tokyo")—that'll cause unexpected behavior! We'll fix that too.
Here's the updated code with proper data storage:
# Initialize an empty array to hold all trip data trips = [] puts "How many trips did you take?" trip_count = gets.chomp.to_i trip_count.times do |x| puts "Where did you go for trip ##{x+1}?" trip_location = gets.chomp # No to_i here—locations are strings! puts "How much did you spend on lodging?" lodging_cost = gets.chomp.to_i # Create a hash for this trip's details and add it to the trips array trip_details = { location: trip_location, lodging: lodging_cost # We can add more keys later for other expenses, like transportation! } trips << trip_details end
Why this works:
- The
tripsarray acts as a container for every trip you record. Each entry in the array is a hash that stores specific details about one trip. - Hashes let you label each piece of data (like
:locationor:lodging), so you can easily retrieve values later by their key.
Using the stored data later:
Once you've collected all trips, you can loop through the array to display details, calculate totals, etc. For example:
# Calculate total lodging cost across all trips total_lodging = trips.sum { |trip| trip[:lodging] } puts "Total spent on lodging across all trips: $#{total_lodging}" # Print each trip's details puts "\nAll your trip details:" trips.each_with_index do |trip, index| puts "Trip ##{index+1}: #{trip[:location]} | Lodging: $#{trip[:lodging]}" end
Adding more expenses (like transportation):
Since we're using hashes, expanding to include other costs is straightforward. Just add more prompts and hash keys:
trip_count.times do |x| # ... existing location and lodging prompts ... puts "How much did you spend on transportation?" transport_cost = gets.chomp.to_i trip_details = { location: trip_location, lodging: lodging_cost, transportation: transport_cost # New key for transportation } trips << trip_details end
This structure keeps your data organized and flexible as you add more features to your program!
内容的提问来源于stack exchange,提问作者Petrarahim Carnes

