gpt4 book ai didi

Ruby:数组数组到哈希数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:57 24 4
gpt4 key购买 nike

我有一个数组的数组(从 CSV 文件导入):

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

并希望将其转换为哈希数组,例如:

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

我使用了下面的代码,但它不起作用:

    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

但是我得到:

> 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>'

这有什么问题吗?如何使用 .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

关于Ruby:数组数组到哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24512252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com