将文件读入关联数组

时间:2014-04-17 23:55:48

标签: ruby arrays hash

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

我的文件格式如下:

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

唯一的问题是我不知道怎么做。到目前为止,我有:

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

哪个接近我想要的,但仍然无法将其变为可用于我的格式。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以尝试这样的事情: -

enter code here
fh = File.open("scores.txt","r")
rh={} #result Hash
fh.readlines.each{|line|
kv=line.split(/\s+/)
puts kv.length
rh[kv[0]] = kv[1..kv.length-1].join(",") #***store the values joined by ","
}
puts rh.inspect
fh.close

如果要获取值数组,请将循环中的最后一行替换为     rh [kv [0]] = kv [1..kv.length-1]

答案 2 :(得分:0)

可以用3行完成(这就是我爱Ruby的原因)

scores = File.readlines('/scripts/test.txt').map{|l| l.split(/\s+/)}
headers = scores.shift
scores.map!{|score|Hash[headers.zip(score)]}

现在scores包含您的哈希数组

这是一个详细解释

#open the file and read 
#then split on new line 
#then create an array of each line by splitting on space and stripping additional whitespace
scores = File.open('scores.txt', &:read).split("\n").map{|l| l.split(" ").map(&:strip)}
#shift the array to capture the header row
headers = scores.shift
#initialize an Array to hold the score hashs
scores_hash_array = []
#loop through each line
scores.each do |score|
  #map the header value based on index with the line value 
  scores_hash_array << Hash[score.map.with_index{|l,i| [headers[i],l]}]
end
#=>[{"KeyName"=>"Key1", "Val1Name"=>"Val1-1", "Val2Name"=>"Val2-1", "..."=>"...", "ValMName"=>"ValM-1"},
    {"KeyName"=>"Key2", "Val1Name"=>"Val1-2", "Val2Name"=>"Val2-2", "..."=>"...", "ValMName"=>"ValM-2"},
    {"KeyName"=>"Key3", "Val1Name"=>"Val1-3", "Val2Name"=>"Val2-3", "..."=>"...", "ValMName"=>"ValM-3"},
    {"KeyName"=>"..", "Val1Name"=>"..", "Val2Name"=>"..", "..."=>"..", "ValMName"=>".."},
    {"KeyName"=>"KeyN", "Val1Name"=>"Val1-N", "Val2Name"=>"Val2-N", "..."=>"...", "ValMName"=>"ValM-N"}]

scores_hash_array现在在工作表中的每一行都有一个哈希值。