rename a csv file in ruby

To rename a CSV file in Ruby, you can make use of the File#rename method. It takes two arguments: the current name of the file, and the new name you want to give it.

Here's an example code snippet that demonstrates how to rename a CSV file:

main.rb
require 'csv'

current_file_name = 'old_file_name.csv'
new_file_name = 'new_file_name.csv'

# Read the CSV from the old file
csv_data = CSV.read(current_file_name)

# Write the CSV to the new file
CSV.open(new_file_name, 'w') do |csv|
  csv_data.each do |row|
    csv << row
  end
end

# Delete the old file
File.delete(current_file_name)

puts "File #{current_file_name} has been renamed to #{new_file_name}."
411 chars
20 lines

In the above code, we first declare the names of the old and new files. We then read the CSV data from the old file using CSV.read. Next, we write the CSV data to the new file using CSV.open. We iterate through each row in the data and output it to the new file. Finally, we use File.delete to delete the old file, since it's no longer needed. We output a confirmation message to the console.

Note that you can replace the csv_data.each loop with a single line of code that copies the entire contents of the old file to the new file, like this:

main.rb
File.write(new_file_name, File.read(current_file_name))
56 chars
2 lines

This is a simpler and more efficient method, but it will only work for small files that can be read and written quickly. If you're working with large CSV files, using CSV methods as shown in the first example may be a better choice.

gistlibby LogSnag