简体   繁体   中英

Ruby: Array of Arrays to Array of Hashes

I have an Array of Arrays (imported from CSV file):

[[title1],[title2],[title3],[title4],[title5]],
[[song1],[author1],[bpm1],[key1],[energy1]],
...
[[song100],[author100],[bpm100],[key100],[energy100]].

and would like to convert it to an Array of Hashes like:

[{"title1"=>"song1","title2"=>"author1","title3"=>"bpm1","title4"=>"key1","title5"=>"energy1"}],
...
[{"title1"=>"song100","title2"=>"author100","title3"=>"bpm100","title4"=>"key100","title5"=>"energy100"}].

I used the code below but it doesn't work:

    require 'csv'
    csv=CSV.read('library.csv')

array_hash=[]
hash={}

for i in 1..(csv.size)

  hash1={}

    for n in 0..4

        a=csv[0][n]
        b=csv[i][n]
        hash1[a]=b
        hash.merge!(hash1)

    end

  array_hash.push(hash)

end

But I get:

> NoMethodError: undefined method `[]' for nil:NilClass     from
> (irb):149:in `block (2 levels) in irb_binding'    from (irb):146:in
> `each'    from (irb):146:in `block in irb_binding'    from (irb):143:in
> `each'    from (irb):143  from
> /Users/user/.rvm/rubies/ruby-2.0.0-p481/bin/irb:12:in `<main>'

What is wrong with this? How to do the same using .each ?

The ruby CSV library has a to_hash function on CSV::Row , so you can do as below instead:

require 'csv'
rows = CSV.read('library.csv', headers: true).map(&:to_hash) #rows would return a list of hashes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM