Rectangle 27 0

ruby Convert CSV file into array of hashes?


Hash[ keys.zip(values) ]
ensure in parse': undefined method
parse' 	from C:/Users/Mythago/My Documents/Aptana Studio 3 Workspace/elh stats/main.rb:5:in
test = '''
09.09.2008,1,HC Vitkovice Steel,BK Mlada Boleslav,1:0 (PP)
09.09.2008,1,HC Lasselsberger Plzen,RI OKNA ZLIN,6:2
09.09.2008,1,HC Litvinov,HC Sparta Praha,3:5
'''.strip

keys = ['time', etc... ]
CSV.parse(test).map {|a| Hash[ keys.zip(a) ] }

@user1955522 CSV.parse method accepts string as its argument, not an array. Try CSV.read('data.txt').map {|a| Hash[ keys.zip(a) ]} .

I tried that 'require 'csv' csv_data = CSV.read 'data.txt' keys = ['time',"round","home","visiting","score"] CSV.parse(csv_data).map {|a| Hash[ keys.zip(a) ] }' but i probably didn catch the idea because it returned some errors

Note
Rectangle 27 0

ruby Convert CSV file into array of hashes?


:blank_to_nil
CSV.new(File.new(file), :headers => true, :header_converters => :symbol, :converters => [:all]).to_a.map {|row| row.to_hash }
CSV.new(body, headers: true).map(&:to_hash)
body = "09.09.2008,1,HC Vitkovice Steel,BK Mlada Boleslav,1:0 (PP)
09.09.2008,1,HC Lasselsberger Plzen,RI OKNA ZLIN,6:2
09.09.2008,1,HC Litvinov,HC Sparta Praha,3:5"
csv = CSV.new(body, :headers => true, :header_converters => :symbol, :converters => [:all, :blank_to_nil])
csv.to_a.map {|row| row.to_hash }
=> [{:year=>1997, :make=>"Ford", :model=>"E350", :description=>"ac, abs, moon", :price=>3000.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition\"", :description=>nil, :price=>4900.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition, Very Large\"", :description=>nil, :price=>5000.0}, {:year=>1996, :make=>"Jeep", :model=>"Grand Cherokee", :description=>"MUST SELL!\nair, moon roof, loaded", :price=>4799.0}]

@CodeBiker @shakerlxxv I have the same error message, NoMethodError: undefined method encode for nil:Nilclass. What is the solution to get it working?

And then run his code as listed above on it.

So, you could save the body of your CSV file into a string called body.

Thanks for the post reference, very useful. I'm not sure if it was my data specifically; however, I needed to ommit the :blank_to_nil otherwise I was getting an error *** NoMethodError Exception: undefined method arity' for nil:NilClass`

This is a fantastic post by Josh Nichols which explains how to do what you're asking.

Note
Rectangle 27 0

ruby Convert CSV file into array of hashes?


CSV.foreach(data_file, headers: true) do |row|
  puts row.inspect # hash
end

(Tested with Ruby 2.0, but I think this has worked for quite a while.)

From there, you can manipulate the hash however you like.

Technically, I think each row is an instance of CSV::Row, which acts like a Hash but doesn't actually inherit Hash.

Thanks for this! I could not find this option and I was banging my head against it quite hard

You can also use CSV.parse(data, headers: true).map(&:to_h) to similar effect, taking into account Jared's note above. This turns your CSV into an array of hashes with headers as keys. You can also want to toss in the option header_converters: :symbol to use symbols as keys instead of the column name as strings.

You say you don't have any headers - could you add a header line to the beginning of the file contents after reading them?

Note
Rectangle 27 0

ruby Convert CSV file into array of hashes?


keys = [:key1, :key2, ... ]
arr_of_hashers = CSVHasher.hashify('/path/to/csv/file', { keys: keys })
require 'csv_hasher'
arr_of_hashes = CSVHasher.hashify('/path/to/csv/file')

If you want to pass your own keys then

The keys of the returned hashes will be the header values of the csv file.

You can try the following gem also

Note
Rectangle 27 0

ruby Convert CSV file into array of hashes?


data = CSV.foreach(data_file, headers: true).map{ |row| row.to_h }
data_file = './sheet.csv'
data = []
CSV.foreach(data_file, headers: true) do |row|
  data << row.to_hash
end

Now data is an array of hashes to do your bidding with!

Note