Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read csv from ARGF

Tags:

ruby

csv

In Ruby 1.9 how do I read CSV from ARGF?

I tried the following, but it printed nothing:

require 'csv'
CSV(ARGF).read do |row|
    p row
end
  • http://www.ruby-doc.org/core-1.9.3/ARGF.html
  • http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html
like image 308
Colonel Panic Avatar asked Oct 24 '12 19:10

Colonel Panic


2 Answers

If you want lazy you could try:

CSV.new(ARGF.file).each do |row|
  ...
end

Source:
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#label-Wrap+an+IO+Object

like image 200
Casper Avatar answered Oct 19 '22 23:10

Casper


As it is said in http://www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#label-Wrap+an+IO+Object to use IO (like ARGF) you need to create a new cvs object:

csv = CSV.new(io, options)

An example like this one work fine:

#!/usr/bin/env ruby
#file : readCSV.rb
require "csv"
csv = CSV.new(ARGF, {:col_sep=>";", :headers=>:first_row})
csv.each do |line|
  p line.to_s
end

It can then be use in two ways:

  1. cat path/to/my.csv | ./readCSV.rb | less # for useless use of cat
  2. ./readCSV.rb < path/to/my.csv
  3. ./readCSV.rb path/to/my.csv | less
like image 27
JL M Avatar answered Oct 20 '22 00:10

JL M