# Parsing a CSV file having multiple records in RUBYp

**URL:** <https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410>\
**Category:** Ruby\
**Created:** [December 26, 2006, 8:35am UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410 "2006-12-26T08:35:41Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 8:35am UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/1 "2006-12-26T08:35:41Z")

</div>

Hi everyone,

Can anyone help me in parsing a CSV file,with comma seperated multiple  
records (multiple columns and multiple rows)…

What i am doing is

uploading a CSV file and reading the records from CSV file,first row  
contains field names(database field names),reaing record line by line  
and splitting each record by a comma(since CSV file is a comma seperated  
fields)  
and sending the splitted data into corresponding fields of database.

everything goes well except last column of the record is skipping in my  
logic.

My logic unable to read the last field values and field name.If I put an  
extra

column name,my logic is working well and good.

here is my logic…  
rows=Array.new  
columns=Array.new  
physician= Physician.new // object of physician in to which values are  
send after spilltting.  
File.open(@filepath, “r”) do |f|  
f.each\_line { |line|  
if(count==0)  
header=line.to\_s  
columns=header.split(’,’)  
end  
else  
str=line.to\_s  
rows=str.split(’,’)  
columns.each do |col|  
physician[columns[cnt]]= rows[cnt]  
cnt=cnt+1  
end  
end

Can anyone solve my problem,Its urgent

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 8:55am UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/2 "2006-12-26T08:55:10Z")

</div>

In message “Parsing a CSV file having multiple records in RUBYp”  
on 26.12.2006, Krishna M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
writes:

KM\> Can anyone help me in parsing a CSV file,with comma seperated  
multiple  
KM\> records (multiple columns and multiple rows)…

/usr/local/lib/ruby/1.8/csv.rb

maybe it helps.

regards.  
Karl-Heinz

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 10:17am UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/3 "2006-12-26T10:17:14Z")

</div>

Hi,

The ruby standard library include a CSV parser (you will find the api  
there : [RDoc Documentation](http://www.ruby-doc.org/stdlib/)). You should try it.

require ‘csv’  
CSV.open(@filepath, “r”) do |csv|

# csv[0]…csv[n] contains your columns…

end

Since your file has a header, you could write something like :

require ‘csv’  
my\_csv = CSV.open(@filepath, “r”)  
header = my\_csv.shift # header is a array containing each column of  
your first line  
my\_csv.each do |row|  
row.each\_index { |i| physician[header[i]] = row[i] }  
end  
my\_csv.close

… But be carrefull if your file contains more than one line and you  
didn’t overload the “=” operator of physician because you will affect  
all lines in the same physician object…

Krishna M. a écrit :

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 4:31pm UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/4 "2006-12-26T16:31:37Z")

</div>

On Dec 26, 2006, at 3:15 AM, come wrote:

> Since your file has a header, you could write something like :

Obviously I am biased, but I sure think FasterCSV makes this kind of  
thing easier:

> > require “rubygems”  
> > =\> false
> 
> > require “faster\_csv”  
> > =\> true
> 
> > csv = \<\<END\_CSV  
> > item,in\_stock,reorder\_limit  
> > “Real ““Rubies”””,10,5  
> > Pearls,100,20  
> > Snakes,2,5  
> > END\_CSV  
> > =\> “item,in\_stock,reorder\_limit\n"Real ““Rubies”””,10,5\nPearls,100,20  
> > \nSnakes,2,5\n"
> 
> > result = FCSV.parse(csv, :headers =\> true, :header\_converters  
> > =\> :symbol)  
> > =\> #\<FasterCSV::Table:0x6e570c @mode=:col\_or\_row, @table=  
> > [#\<FasterCSV::Row:0x6e5310 @header\_row=false, @row=[[:item, “Real  
> > “Rubies””], [:in\_stock, “10”], [:reorder\_limit, “5”]]\>,  
> > #\<FasterCSV::Row:0x6e4f00 @header\_row=false, @row=[[:item, “Pearls”],  
> > [:in\_stock, “100”], [:reorder\_limit, “20”]]\>, #\<FasterCSV::Row:  
> > 0x6e4af0 @header\_row=false, @row=[[:item, “Snakes”], [:in\_stock,  
> > “2”], [:reorder\_limit, “5”]]\>]
> 
> > puts re  
> > readline require\_\_ result  
> > readlines require\_gem retry  
> > redo require\_gem\_with\_options return  
> > remove\_instance\_variable rescue  
> > require respond\_to?
> 
> > puts result.map { |row| row[:item] }  
> > Real “Rubies”  
> > Pearls  
> > Snakes  
> > =\> nil
> 
> > result.each { |row| p row.to\_hash }  
> > {:in\_stock=\>“10”, :reorder\_limit=\>“5”, :item=\>“Real “Rubies””}  
> > {:in\_stock=\>“100”, :reorder\_limit=\>“20”, :item=\>“Pearls”}  
> > {:in\_stock=\>“2”, :reorder\_limit=\>“5”, :item=\>“Snakes”}  
> > =\> #\<FasterCSV::Table:0x6e570c @mode=:col\_or\_row, @table=  
> > [#\<FasterCSV::Row:0x6e5310 @header\_row=false, @row=[[:item, “Real  
> > “Rubies””], [:in\_stock, “10”], [:reorder\_limit, “5”]]\>,  
> > #\<FasterCSV::Row:0x6e4f00 @header\_row=false, @row=[[:item, “Pearls”],  
> > [:in\_stock, “100”], [:reorder\_limit, “20”]]\>, #\<FasterCSV::Row:  
> > 0x6e4af0 @header\_row=false, @row=[[:item, “Snakes”], [:in\_stock,  
> > “2”], [:reorder\_limit, “5”]]\>]

James Edward G. II

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 7:42pm UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/5 "2006-12-26T19:42:15Z")

</div>

Hi,

You just start your line and press the tab key :

irb(main):001:0\> toto=5  
=\> 5  
irb(main):002:0\> puts t[tab]  
taint test throw to\_s trace\_var true  
tainted? then to\_a toto trap type  
irb(main):002:0\> puts toto.[tab]  
toto.nil?  
toto. **id** toto.nonzero?  
toto. **send** toto.numerator  
toto.abs toto.object\_id  
toto.between? toto.power!  
toto.ceil toto.prec  
toto.chr toto.prec\_f  
toto.class toto.prec\_i  
toto.clone toto.private\_methods  
toto.coerce toto.protected\_methods  
toto.denominator toto.public\_methods  
toto.display toto.quo  
toto.div toto.rdiv  
toto.divmod toto.remainder  
toto.downto toto.require  
toto.dup toto.require\_gem  
toto.eql? toto.respond\_to?  
toto.equal? toto.round  
toto.extend toto.rpower  
toto.floor toto.send  
toto.freeze toto.singleton\_method\_added  
toto.frozen? toto.singleton\_methods  
toto.gcd toto.size  
–More–

matt a écrit :

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 6:09pm UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/6 "2006-12-26T18:09:54Z")

</div>

James,

Not to be off topic, but how did you get an ‘auto complete’ type shell ?

I tried it at home and it didn’t do what your output shows… I’m  
jealous.

It almost looks like you overloaded puts …

Is there a big secret to share? I’d even settle of a little secret.  
I’m not picky!

Matt

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 26, 2006, 10:16pm UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/7 "2006-12-26T22:16:39Z")

</div>

James Edward G. II wrote:

> =\> true  
> =\> #\<FasterCSV::Table:0x6e570c @mode=:col\_or\_row, @table=  
> remove\_instance\_variable rescue  
> =\> #\<FasterCSV::Table:0x6e570c @mode=:col\_or\_row, @table=  
> [#\<FasterCSV::Row:0x6e5310 @header\_row=false, @row=[[:item, “Real  
> “Rubies””], [:in\_stock, “10”], [:reorder\_limit, “5”]]\>,  
> #\<FasterCSV::Row:0x6e4f00 @header\_row=false, @row=[[:item, “Pearls”],  
> [:in\_stock, “100”], [:reorder\_limit, “20”]]\>, #\<FasterCSV::Row:  
> 0x6e4af0 @header\_row=false, @row=[[:item, “Snakes”], [:in\_stock,  
> “2”], [:reorder\_limit, “5”]]\>]

class String  
def csv  
(self + “,”).scan(  
/("(?:[^"]+|"")_"|[^,]_),/).flatten.  
map{|s| s.gsub(/\A"|"\Z/,’’).gsub(/""/,’"’)}  
end  
end

data = DATA.readlines.map{|s| s.chomp.csv}  
header = data.shift  
p header  
p data  
puts  
data.map{|a| header.zip(a).inject({}){|h,x|  
h.merge({x[0].to\_sym,x[1]}) }}.  
each{|h| p h}

**END**  
item,in\_stock,reorder\_limit  
“Real ““Rubies”””,10,5  
Pearls,100,20  
Snakes,2,5

— output -----  
[“item”, “in\_stock”, “reorder\_limit”]  
[[“Real “Rubies””, “10”, “5”], [“Pearls”, “100”, “20”], [“Snakes”,  
“2”, “5”]]

{:in\_stock=\>“10”, :reorder\_limit=\>“5”, :item=\>“Real “Rubies””}  
{:in\_stock=\>“100”, :reorder\_limit=\>“20”, :item=\>“Pearls”}  
{:in\_stock=\>“2”, :reorder\_limit=\>“5”, :item=\>“Snakes”}

---

<div class="post-metadata">

**Author:** ![mundrakrishna](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/73ab20/32.png) [@mundrakrishna](https://www.ruby-forum.com/u/mundrakrishna)\
**Post date:** [December 27, 2006, 1:41am UTC](https://www.ruby-forum.com/t/parsing-a-csv-file-having-multiple-records-in-rubyp/80410/8 "2006-12-27T01:41:01Z")

</div>

On Dec 26, 2006, at 11:09 AM, matt wrote:

> Is there a big secret to share? I’d even settle of a little secret.  
> I’m not picky!

[http://wiki.rubygarden.org/Ruby/page/show/Irb/TipsAndTricks](http://wiki.rubygarden.org/Ruby/page/show/Irb/TipsAndTricks)

😉

James Edward G. II
