Jes Jes - 2 months ago 12
Ruby Question

Ruby - reading CSV from STDIN

I'm trying to read from .CSV file and create objects with attributes of every row.
My code works fine:

def self.load_csv
puts "Name of a file?"
filename = STDIN.gets.chomp
rows = []
text = File.read(filename).gsub(/\\"/,'""')
CSV.parse(text, headers: true, header_converters: :symbol) do |row|
row = row.to_h
row = row.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
rows << row
end

rows.map do |row|
Call.new(row)
end
end
end


Now I wanted to take filename from STDIN. I simply changed:

def self.load_csv(filename)
rows = []
text = File.read(filename).gsub(/\\"/,'""')
CSV.parse(text, headers: true, header_converters: :symbol) do |row|
row = row.to_h
row = row.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
rows << row
end

rows.map do |row|
Call.new(row)
end
end
end


and when I try ruby program.rb filename.csv I got error no implicit conversion of String into IO, and after removing line with
File.read
it does nothing - like an infinite loop maybe? Of course I invoke ceratain methods with STDIN argument in different parts of the code. I used similiar code for reading from STDIN with success in the past, what am I doing wrong this time?

Answer

This code is working:

require 'csv'

class Call
  def initialize(args)
  end
end

def load_csv(filename)
  rows = []
  text = File.read(filename).gsub(/\\"/,'""')
  CSV.parse(text, headers: true, header_converters: :symbol) do |row|
    row = row.to_h
    row = row.each_with_object({}){ |(k,v), h| h[k.to_sym] = v }
    rows << row
  end

  rows.map { |row| Call.new(row) }
end

filename = ARGV[0]
load_csv(filename)
Comments