2011-07-20 56 views
2

外部文件中的特定線I有這樣的代碼:雷丁從紅寶石IO

File.foreach("testfile.txt") { |line| print line } 
lines = File.readlines("testfile.txt") 
lines.each { |line| print line } 

例我怎麼能編輯這個到testfile.txt得到特定的行?

$text2 = gets("some code to give me text on line 2 from textfile.txt").chomp 

所以,我想運行一個程序,搜索任何人都可編輯的4個不同的變量。這些將在一個單獨的文件中,因此代碼將不必重寫,以便更改一組新搜索案例的測試。

說我有一個文件(我想文字是最簡單的,但我可能是錯的),看起來像這樣:

Tea 

Coffee 

Hot Chocolate 

Cookies 

這將是所有這些都是在文件中。而另一個文件(.rb)則會提取這些變量並在Google或其他地方搜索它們。如果代碼以字節讀取,那麼我將無法將變量更改爲更長或更短的任何內容。

這將是有文件可行說

1:Tea 

2:Coffee 

3:Hot Chocolate 

4:Cookies 

只要代碼只拉出「茶」或「咖啡」,而不是前面的數字。

+0

避免使用'$'全局變量,據我所知在Ruby – Arie

回答

3

這聽起來像你不想返回一個符合特定模式的行,但你想通過行號來抓取。

解決方案1:

def read_line_number(filename, number) 
    return nil if number < 1 
    line = File.readlines(filename)[number-1] 
    line ? line.chomp : nil 
end 

解決方案2A - 有些更有效,因爲它不嘗試讀取整個文件:

require 'english' 
def read_line_number_1a(filename, number) 
    found_line = nil 
    File.foreach(filename) do |line| 
    if $INPUT_LINE_NUMBER == number 
     found_line = line.chomp 
     break 
    end 
    end 
    found_line 
end 

解決方案2B - 效率也很高,但功能更強大樣式(儘管我沒有檢查detect是否會讀到文件結尾)

def read_line_number(filename, match_num) 
    found_line, _idx = 
    File.enum_for(:foreach, filename).each_with_index.detect do |_cur_line, idx| 
     cur_line_num = idx+1 
     cur_line_num == match_num 
    end 
    found_line.chomp 
end 

用途:

text = read_line_number("testfile.txt", 2) 
+0

文本文件的格式是什麼? – Benjamin

+0

@ benjamin-shephard我知道如果你使用本地文本文件(即行結尾)運行本地ruby解釋器,它會正常工作;例如在Windows(CRLF)文本文件上的Windows紅寶石將工作。例如,如果您在Linux系統上使用Windows文本,該代碼可能無法正常工作。 – Kelvin

0

你會想要使用lines.grep "some string"。 或者只是lines[x]如果您確切地知道您想要的行號x

+0

中被認爲是壞習慣,哪部分對不起? – Benjamin

0

的解決方案,我擁有的是:

我TESTFILE.TXT讀取


是是做
人,這是真棒

我的.rb文件讀取

a = IO.readlines("testfile.txt").grep(/\w+/)
puts "does it work...."
sleep 2
puts a[2]
sleep 10

0
def read_line_number(filename, number) 
f = File.open(filename) 
l = nil 
begin 
    number.times do 
    l = f.readline.chomp 
    end 
rescue 
puts "End of file reached" 
else 
f.close unless f.nil? 
return l 
end 
end 
+0

爲什麼這個有效?一些解釋會很好 – rayryeng

+0

抱歉關於thet:/ .....這個代碼讀取X行X所以如果你想要一個已知的行這個讀取直到到那裏,並只返回最後一行讀取.. btw ..是這個有效? – Nando