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

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


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 }


CSV.read(file_path, headers:true, header_converters: :symbol, converters: :all).collect do |row|  Hash[row.collect { |c,r| [c,r] }]end



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