How to remove redundant file open operation in ruby

49 views Asked by At

I made a ruby program to copy content of one CSV file to a new CSV file.

This is my code -

require 'csv'
class CopyFile
  def self.create_duplicate_file(file_name)

    CSV.open(file_name, "wb") do |output_row|
      output_row << CSV.open('input.csv', 'r') { |csv| csv.first }
      CSV.foreach('input.csv', headers: true) do |row|
      output_row << row
      end
    end
  end
end

puts "Insert duplicate file name"
file_name = gets.chomp
file_name = file_name+".csv"
CopyFile.create_duplicate_file(file_name)

puts "\nDuplicate File Created."

I am opening the input.csv file twice, one to copy headers and then to copy content.

I want to optimise my code. So is there a way to optimise it further?

1

There are 1 answers

1
Thermatix On

Just use the cp method: FileUtils.cp(src, destination, options), no need to reinvent the wheel, like this:

class CopyFile
  def self.create_duplicate_file(file_name)
    FileUtils.cp('input.csv',file_name)
  end
end

or better yet:

file_name = gets.chomp
file_name = file_name+".csv"
FileUtils.cp('input.csv', file_name)