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

前端 未结 6 1289
萌比男神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
    闹比i (楼主)
    2021-01-31 04:40

    Not as 1-liner-ie but this was more clear to me.

    csv_headers = CSV.parse(STDIN.gets)
    csv = CSV.new(STDIN)
    
    kick_list = []
    csv.each_with_index do |row, i|
      row_hash = {}
      row.each_with_index do |field, j|
        row_hash[csv_headers[0][j]] = field
      end
      kick_list << row_hash
    end
    

提交回复
热议问题