CSV processing in Ruby
Ruby is a relatively young language. One of the advantages with this is that Ruby has libraries for common programming needs. In this post, I will show you how easy it is to process CSV files in Ruby.
A CSV file contains comma separated values and is an easy way to store information in text files. In many Web applications, CSV file is generated and is output as excel filetype so that Microsoft excel program can process it.
For this example, let us consider the following CSV file. It contains exam results of 3 students.
Jayson Joseph,39,fail
Thomas Mathew,92,pass
Ravikumar,83,pass
Save this as examresults.txt. Following program shows how this can be read using Ruby. In this example, we will read the exam results, print the name of the people who failed the exam and finally add one more entry to the exam results file. All this can be achieved with minimal plumbing code!
require "csv"
class CSVExamResults
def initialize(filename)
puts "setting filename=",filename
@filename = filename
end
def printExamResults
@results = CSV.read(@filename)
puts @results.inspect
end
def printFailedGuys
failed = @results.find_all do |r|
r[2]=="fail"
end
puts "Following guys failed the exam:"
failed.each {|m| puts m[0]}
end
def addSampleResult
@results << ["Reema","76","pass"]
CSV.open(@filename, 'w') do |csv|
@results.each do |result|
csv << result
end
end
end
c1 = CSVExamResults.new("examresults.txt")
c1.printExamResults # displays CSV as two dimensional array
c1.printFailedGuys # this prints the names of the guys who failed!
c1.addSampleResult()
c1.printExamResults # print updated csv file
end
Check out the documentation for complete set of methods available in csv library!
Hey, I am about to apply your example, seems very effective ! Above all thanks for sharing, this post will be my kickstart with CSV
For the record.. it took to me 13.0 sec to open a file with 3.000 lines, about 20 columns, lots of emptys, whit half of my HP 1.6 Ghz working, about 1MB memmory usage increased, no ruby process priority were changed..
Well.. pretty effective for what i need considering that for our happiness ruby doesn’t compile =D
Do you know how to delete a line in a CSV file after it has been created?