FasterCSV.foreach lineno?

B

Bil Kleb

OK, so I can't think my way out of a paper this morning.

Can I access FasterCVS#lineno while inside a foreach?

For example,

$ cat << EOF > csv_file
one
two
three
EOF

$ ruby -rubygems \
-e'require "fastercsv";FasterCSV.foreach("csv_file")\
{|r| puts "lineno somehow"}'

Thanks,
 
R

Rob Biedenharn

OK, so I can't think my way out of a paper this morning.

Can I access FasterCVS#lineno while inside a foreach?

For example,

$ cat << EOF > csv_file
one
two
three
EOF

$ ruby -rubygems \
-e'require "fastercsv";FasterCSV.foreach("csv_file")\
{|r| puts "lineno somehow"}'

Thanks,

Bil,

Since it looks like the answer to your first question is "No.", what
if you defined:

class FasterCSV
def self.foreach_with_lineno(path, options = Hash.new, &block)
open(path, options) do |csv|
csv.each {|line| block[line, csv.lineno]}
end
end
end

irb> FasterCSV.foreach_with_lineno("csv_file") {|r,l| puts "#{l}: #{r}"}
1: one
2: two
3: three
=> nil

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 
J

James Gray

OK, so I can't think my way out of a paper this morning.

Can I access FasterCVS#lineno while inside a foreach?

No, but you can switch to an each() iterator and get at it that way
(just as you would with an IO object):

$ cat data.csv
one
two
three
$ cat fcsv_example.rb
#!/usr/bin/env ruby -wKU

require "rubygems"
require "faster_csv"

FCSV.open("data.csv") do |csv|
csv.each do |row|
puts "#{csv.lineno}: #{row}"
end
end
$ ruby fcsv_example.rb
1: one
2: two
3: three

Hope that helps.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,131
Latest member
KatlynC08

Latest Threads

Top