0

我有一个 txt 记录文件:

firstname lastname dob ssn status1 status2 status3 status4 firstname lastname dob ...

我可以把它变成一个数组:

tokens[0] = firstname
...
tokens[8] = firstname (of record 2).  
tokens[9] = lastname (of record 2) and so on.

我想逐步迭代tokens数组,所以我可以说:

record1 = tokens[index] + tokens[index+1] + tokens[index+2] etc.

并且该步骤(在上面的示例 8 中)将处理记录:

record2, record3 etc etc.

step 0 index is 0
step 1 (step set to 8 so index is 8)
etc.

我想我应该说这些记录来自我称为 .split 的 txt 文件:

file = File.open(ARGV[0], 'r')
line = ""
while !file.eof?
   line = file.readline
end
##knowing a set is how many fields, do it over and over again.

tokens = line.split(" ")
4

2 回答 2

4

这有帮助吗?

tokens = (1..80).to_a #just an array
tokens.each_slice(8).with_index {|slice, index|p index; p slice}
#0
#[1, 2, 3, 4, 5, 6, 7, 8]
#1
#[9, 10, 11, 12, 13, 14, 15, 16]
#...
于 2013-04-12T15:43:07.607 回答
2

使用each_slice您还可以将变量分配给块内的字段:

tokens.each_slice(8) { |firstname, lastname, dob, ssn, status1, status2, status3, status4|
  puts "firstname: #{firstname}"
}
于 2013-04-12T16:01:19.897 回答