Ruby实现CSV文件按邮箱定位并编辑指定字段的技术问询
Solution for Editing CSV Rows by Email
Here's how to extend your existing code to support editing fields once the target row is located:
- Check for valid row: Handle cases where the input email doesn't match any entry.
- Display current data: Show the user the row they're about to modify.
- Validate field selection: Ensure the user picks a valid column from the CSV headers.
- Update the field: Accept the new value and modify the row.
- Save changes: Write the updated dataset back to the original CSV file.
Full Implementation Code
require "csv" # Read CSV with headers enabled csv_data = CSV.read('cars.csv', headers: true) # Get user's target email puts "Enter the email to locate the row:" target_email = gets.chomp # Find the matching row target_row = csv_data.find { |row| row['email'] == target_email } if target_row.nil? puts "No row found with email: #{target_email}" exit end # Show current row details puts "\nCurrent row data:" target_row.each { |field, value| puts "#{field}: #{value}" } # List editable fields available_fields = target_row.headers puts "\nAvailable fields to edit: #{available_fields.join(', ')}" # Get valid field selection from user selected_field = nil until available_fields.include?(selected_field) puts "Enter the field you want to edit:" selected_field = gets.chomp.downcase # Allow case-insensitive input end # Get new value for the selected field puts "Enter the new value for #{selected_field}:" new_value = gets.chomp # Update the row (uses hash-like access for CSV::Row) target_row[selected_field] = new_value # Write updated data back to CSV CSV.open('cars.csv', 'w', headers: true, write_headers: true) do |csv| csv << available_fields csv_data.each { |row| csv << row } end puts "\nSuccessfully updated #{selected_field} to #{new_value} for email #{target_email}"
Key Notes
- Hash-like row handling:
CSV::Rowobjects behave like hashes, so you can modify values directly usingrow[field_name] = new_value. - Input validation: The loop ensures the user can't enter an invalid field name.
- File write: We overwrite the original file with the full updated dataset, preserving the original header structure.
内容的提问来源于stack exchange,提问作者burner
相关产品推荐
相关产品推荐

