2013-05-27 64 views
0

我一直在試圖打開文件,讀取內容,然後對該文件的內容進行編號並保存。因此,例如,該文件包含:將號碼預先存入文件

This is line 1. 

This is line 2. 

This is line 3. 

輸出應爲:

  1. 這是第1行
  2. 這是第2行
  3. 這是線3

我對ruby非常陌生,所以我只能將行添加到數組中。但是現在我不知道如何爲數組的每個項目添加數字。這裏是我有:

class AddNumbers 
    def insert_numbers_to_file(file) 
    @file_array = [] 
    line_file = File.open(file) 
    line_file.each do |line| 
     @file_array << [line] 
    end 
    end 
end 

任何幫助或暗示,將不勝感激。 謝謝

+0

它的工作原理,你期待什麼呢?如果不是,你得到的結果是什麼? –

回答

0

magic variable $.是你的票在這裏騎:

class AddNumbers 
    def insert_numbers_to_file(file) 
    @file_array = [] 
    line_file = File.open(file) 
    line_file.each do |line| 
     @file_array << "#{$.}: #{line}" 
    end 
    @file_array 
    end 
end 
1

普查員有#each_with_index方法,您可以使用:

class AddNumbers 
    def insert_numbers_to_file(file) 
    @file_array = [] 
    File.open(file).each_with_index do |line, index| 
     @file_array << "%d. %s" % [index, line] 
    end 
    end 
end 
+0

啊,謝謝這是一個開始的好地方!現在只需要弄清楚如何從1而不是0開始索引,並將其寫入文件。 –

+0

所以我宣佈索引的值爲1之前的do循環並增加它。這解決了編號問題,但是,我將如何獲取輸出並用它替換原始文件? –

+0

最簡單的方法是以寫模式('open(file,'w')')重新打開文件,然後將你的@file_array緩衝區寫回去(或者通過將它加入換行符或迭代它) 。 –