CSV In Ruby - Doubt

1

Good afternoon guys, I'm having a hard time understanding how Ruby works with csv, I need to read a file and import the data from that file into a variable

I have a file named die.txt so

Id | Nome | Endereco

1 | Renato | Alameda das magnolias

Both separated by \ t

I put the | to separate just to exemplify

Then I created a class called parser in parse.rb

require 'csv'

Class Parser  

attr_reader :file

def initialize(file)
 begin
   @file = File.open(file) 
 rescue Exception => exception
   raise Exception, "Failed to load file#{exception}" 
 end
end

def parse
 CSV.foreach(@file, {headers: true, header_converters: :symbol, col_sep: '\t', }) do |row|
    p row[:id]
    p row[:nome]
    ...
end 

end

But when I instantiate the Parser class, I call parse method I can not return the columns the idea is to throw the records into an array or hash to save in a database later.

Can anyone give me a hint of where I'm going wrong? I've never had problems with Ruby but I'm now working with CSV Thank you for your attention.

The idea is to abstract this class to read CSV files sent by forms, and insert the data into the database

    
asked by anonymous 09.02.2017 / 16:41

1 answer

0

Good evening,

First, in this code you posted I detected two syntax errors:

  • The keyword Class is in lower case: class

  • end is missing in method parse . One for the block do and another for the end of the method definition.

  • Going straight to the problem, what happens is that the Ruby language only recognizes the escape character \t (among others) when the string is enclosed in double quotes (see here ).

    So, this code will work:

    require 'csv'
    
    class Parser  
    
        attr_reader :file
    
        def initialize(file)
         begin
           @file = File.open(file) 
         rescue Exception => exception
           raise Exception, "Failed to load file#{exception}" 
         end
        end
    
        def parse
         CSV.foreach(
            @file, 
            {
                headers: true, 
                header_converters: :symbol, 
                col_sep: "\t"
            }) do |row|
                next if row.empty?
                puts row[:id]
                puts row[:nome]
            end
    
        end 
    
    end
    
    parse = Parser.new(__dir__ + '/dado.txt')
    parse.parse
    #=> 1
    #=> Renato
    

    I took the liberty of putting a conditional ( next if row.empty? ) to skip the iteration of the loop when the line is empty (in its example, there is an empty line between the header and the beginning of the data).

    I hope it helps.

        
    11.02.2017 / 22:15