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

前端 未结 6 1298
萌比男神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条回答
  •  死守一世寂寞
    2021-01-31 04:26

    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 }
    

提交回复
热议问题