2

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 ?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Uh, yeah, I mean this works if you actually want to use what the standard library gives you. :-) Good answer... I didn't even realize that there was a to_hash function on CSV::Row. I'm deleting my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.