Vishal Mishra Vishal Mishra - 7 months ago 59
Ruby Question

How to compare data in two CSV files

I have two CSV files which have the same structure and ideally should have the same data.

I want to compare the data in them using Ruby and wanted to know if we already have a Ruby function for the same.


As Summea commented, look at the CSV class.

Then use:

#Will store each line of each file as an array of fields (so an array of arrays).
file1_lines ="file1.csv")
file2_lines ="file2.csv")

for i in 0..file1_lines.size
  if (file1_lines[i] == file2_lines[i]
    puts "Same #{file1_lines[i]}"
    puts "#{file1_lines[i]} != #{file2_lines[i]}"

Note that using for in Ruby is quite rare. You normally iterate using an each on the collections, but there are two of them here.

Also, pay attention that one of the list may be longer than the other, but this should get you started.