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

如何在Ruby旅行费用程序中存储多组用户旅行相关输入?

How to Store Multiple Trip Entries in Your Ruby Expense Tracker

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 trips array 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 :location or :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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:02:41