ele*_*ify 2 ruby csv arrays hash
我有一个数组(从CSV文件导入):
[[title1],[title2],[title3],[title4],[title5]],
[[song1],[author1],[bpm1],[key1],[energy1]],
...
[[song100],[author100],[bpm100],[key100],[energy100]].
Run Code Online (Sandbox Code Playgroud)
并希望将其转换为哈希数组,如:
[{"title1"=>"song1","title2"=>"author1","title3"=>"bpm1","title4"=>"key1","title5"=>"energy1"}],
...
[{"title1"=>"song100","title2"=>"author100","title3"=>"bpm100","title4"=>"key100","title5"=>"energy100"}].
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码,但它不起作用:
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
Run Code Online (Sandbox Code Playgroud)
但我得到:
> 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>'
Run Code Online (Sandbox Code Playgroud)
这有什么问题?如何使用.each做同样的事情?
ruby CSV库有一个to_hash函数CSV::Row,所以你可以改为:
require 'csv'
rows = CSV.read('library.csv', headers: true).map(&:to_hash) #rows would return a list of hashes
Run Code Online (Sandbox Code Playgroud)