Handling CSV

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

kalyan c. wrote in post #1003892:

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

Notice that you’re using results.first. This is just getting the first
object out of the results array (it’s a Ruby Array instance). If you
look at the docs on Github for csv-mapper you’ll see that the array
contains Struct objects:

http://www.ruby-doc.org/core/classes/Array.html
http://www.ruby-doc.org/core/classes/Struct.html

So all you need to do is iterate over the array using the “each” method:

results.each do |row|
puts row.first_name
puts row.last_name
puts row.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