2013-04-12 18 views
0

我有記錄的txt文件:ruby​​數組可以each_with_index做步嗎?

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(" ") 
+0

你能重新編輯你的代碼?也給你java代碼和期望的輸出,它在Java中看起來如何。可能這會很好的回答你的速度。 –

回答

2

使用each_slice你也可以指定塊內變量的字段:

tokens.each_slice(8) { |firstname, lastname, dob, ssn, status1, status2, status3, status4| 
    puts "firstname: #{firstname}" 
} 
+0

是完美的謝謝! – Codejoy

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] 
#...