#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2009
    Posts
    3
    Rep Power
    0

    CSV to hash - then output hash


    Hi all,

    Completely new to ruby so apologies for the newbie question. I have a basic csv file:

    Code:
    ID, Name, DOB
    1, Joe, 1/1/1990
    2, Jack, 2/2/1980
    I want to read this CSV into a hash, so I can later pass the hash to a web service. Currently I have.

    Code:
    require 'csv'	
    
    csvfile = {}
    	CSV.foreach("testfile.csv", :headers => true, :header_converters => :symbol, :converters => :all) do |row|
    	csvfile[row.fields[0]] = Hash[row.headers[1..-1].zip(row.fields[1..-1])]
    	puts row.inspect
    end
    How can I output each hash individually to know that it is working correctly? Can these be assigned to a variable which I can then print to screen?

    Thanks!
    andyniko
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2009
    Posts
    3
    Rep Power
    0
    Sorry answered my own question

    Code:
    puts csvfile["row"][:header]

IMN logo majestic logo threadwatch logo seochat tools logo