Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import from CSV into Ruby array, with 1st field as hash key, then lookup a field's value given header row

Maybe somebody can help me.

Starting with a CSV file like so:

Ticker,"Price","Market Cap" ZUMZ,30.00,933.90 XTEX,16.02,811.57 AAC,9.83,80.02 

I manage to read them into an array:

require 'csv' tickers = CSV.read("stocks.csv", {:headers => true, :return_headers => true, :header_converters => :symbol, :converters => :all} ) 

To verify data, this works:

puts tickers[1][:ticker] ZUMZ 

However this doesn't:

puts tickers[:ticker => "XTEX"][:price] 

How would I go about turning this array into a hash using the ticker field as unique key, such that I could easily look up any other field associatively as defined in line 1 of the input? Dealing with many more columns and rows.

Much appreciated!

like image 322
Marcos Avatar asked Dec 12 '11 15:12

Marcos


1 Answers

Like this (it works with other CSVs too, not just the one you specified):

require 'csv'  tickers = {}  CSV.foreach("stocks.csv", :headers => true, :header_converters => :symbol, :converters => :all) do |row|   tickers[row.fields[0]] = Hash[row.headers[1..-1].zip(row.fields[1..-1])] end 

Result:

{"ZUMZ"=>{:price=>30.0, :market_cap=>933.9}, "XTEX"=>{:price=>16.02, :market_cap=>811.57}, "AAC"=>{:price=>9.83, :market_cap=>80.02}} 

You can access elements in this data structure like this:

puts tickers["XTEX"][:price] #=> 16.02 

Edit (according to comment): For selecting elements, you can do something like

 tickers.select { |ticker, vals| vals[:price] > 10.0 } 
like image 186
Michael Kohl Avatar answered Oct 04 '22 11:10

Michael Kohl