gpt4 book ai didi

ruby - 将文件读入关联数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:56 25 4
gpt4 key购买 nike

我希望能够将文件读入关联数组,在关联数组中我可以通过列标题名称访问元素。

我的文件格式如下:

KeyName    Val1Name   Val2Name  ...  ValMNameKey1       Val1-1     Val2-1    ...  ValM-1Key2       Val1-2     Val2-2    ...  ValM-2   Key3       Val1-3     Val2-3    ...  ValM-3..         ..         ..        ..    ..KeyN       Val1-N     Val2-N    ...  ValM-N

The only problem is I don't have a clue how to do it. So far I have:

scores = File.read("scores.txt")
lines = scores.split("\n")
lines.each { |x|
y = x.to_s.split(' ')
}

这接近我想要的,但仍然无法将其转换为我可以使用的格式。

最佳答案

f = File.open("scores.txt") #get an instance of the file
first_line = f.gets.chomp #get the first line in the file (header)
first_line_array = first_line.split(/\s+/) #split the first line in the file via whitespace(s)
array_of_hash_maps = f.readlines.map do |line|
Hash[first_line_array.zip(line.split(/\s+/))]
end
#read the remaining lines of the file via `IO#readlines` into an array, split each read line by whitespace(s) into an array, and zip the first line with them, then convert it into a `Hash` object, and return a collection of the `Hash` objects
f.close #close the file

puts array_of_hash_maps #print the collection of the Hash objects to stdout

关于ruby - 将文件读入关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23145373/

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