Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing CSV data in Ruby hash

Tags:

ruby

hash

Say I have a CSV file with 4 fields,

ID,name,pay,age

and about 32,000 records.

What's the best way to stick this into a hash in Ruby?

In other words, an example record would look like:

{:rec1 => {:id=>"00001", :name => "Bob", :pay => 150, :age => 95 } }

Thanks for the help!

like image 633
mbm Avatar asked Jun 24 '26 19:06

mbm


1 Answers

You can use the Excelsior rubygem for this:

csv = ...
result = Hash.new
counter = 1
Excelsior::Reader.rows(csv) do |row|
   row_hash = result[("rec#{counter}".intern)] = Hash.new

   row.each do |col_name, col_val|
      row_hash[col_name.intern] = col_val
   end
   counter += 1
end

# do something with result...
like image 138
Jacob Relkin Avatar answered Jun 27 '26 08:06

Jacob Relkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!