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

前端 未结 6 1291
萌比男神i
萌比男神i 2021-01-31 04:17

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
         


        
6条回答
  •  梦毁少年i
    2021-01-31 04:43


    To add on to Michael Kohl's answer, if you want to access the elements in the following manner

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

    You can try the following code snippet:

    CSV.foreach("Workbook1.csv", :headers => true, :header_converters => :symbol, :converters => :all) do |row|
        hash_row =  row.headers[1..-1].zip( (Array.new(row.fields.length-1, row.fields[0]).zip(row.fields[1..-1])) ).to_h
        hash_row.each{|key, value| tickers[key] ? tickers[key].merge!([value].to_h) : tickers[key] = [value].to_h}
    end
    

提交回复
热议问题