How to parse the data from CSV file to script

Hi all ,
I am new to ruby , i had a following requirement
i had a csv file which contains the data(3 columns) which need to be
passed for every iteration
CSV file contains
a,b,c
d,e,f
g,h,i
i need output like this.
for first iteration
a
b
c
for second iteration
d
e
f

my sample code looks like this

require ‘rubygems’
require ‘csv-mapper’
require ‘csv’
include CsvMapper
results = import(‘file.csv’) do
start_at_row 1
[first_name, last_name, age]
end
puts results.first.first_name
puts results.first.last_name
puts results.first.age
the above code displays
a
b
c

I need in the loop which displays for all the lines from csv in same
manner

suggest me if there is there any good approach

require ‘stringio’

data =<<“ENDOFSTRING”
a,b,c
d,e,f
g,h,i
ENDOFSTRING

f = StringIO.new(data) #f is just like your open file

f.each do |line|
puts line.split(/\s*,\s*/)
puts ‘-’ * 5
end

f.close

–output:–
a
b
c

d
e
f

g
h
i

  1. Using CsvMapper:

my sample code looks like this

require ‘rubygems’
require ‘csv-mapper’
require ‘csv’
include CsvMapper
results = import(‘file.csv’) do
start_at_row 1
[first_name, last_name, age]
end
puts results.first.first_name
puts results.first.last_name
puts results.first.age
the above code displays
a
b
c

I need in the loop which displays for all the lines from csv in same
manner

suggest me if there is there any good approach

I think you just need to do this:

require ‘rubygems’
require ‘csv’
require ‘csv-mapper’
include CsvMapper

results = import(‘file.csv’) do
start_at_row 1
[first_name, last_name, age]
end

results.each do |record|
puts record.first_name
puts record.last_name
puts record.age
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs