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

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:

  1. Check for valid row: Handle cases where the input email doesn't match any entry.
  2. Display current data: Show the user the row they're about to modify.
  3. Validate field selection: Ensure the user picks a valid column from the CSV headers.
  4. Update the field: Accept the new value and modify the row.
  5. 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::Row objects behave like hashes, so you can modify values directly using row[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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:21:11