2015-10-05 31 views
-2

我想讀入字符串,然後遍歷字符串的每一行。我有以下幾點:將文件讀入每行中的字符串

file = File.read('test.txt') 
    file.each_line { |line| 
    if line.include?(test) 
     puts line 
    end 

我得到的錯誤:

`include?': no implicit conversion of Array into String (TypeError) 
+0

什麼是'test',什麼是'test.txt'的內容? – Stefan

+0

你的問題是什麼? – sawa

回答

5
File.readlines('test.txt').each do |line| 
    puts line 
end 

或者,這在你的情況:

File.readlines('test.txt').each do |line| 
    if line.include? test 
    puts line 
    end 
end 

附: 你說你得到錯誤'包括':陣列中的隱式轉換成字符串(類型錯誤)

這可能是因爲你的test變量是一個數組,而不是一個字符串 重現你的錯誤:

test = [1,2,3] #a mistake, It should be string, like '12' 
File.readlines('test.txt').each do |line| 
    if line.include? test 
    puts line 
    end 
end 
0

無論在test需要是一個單一的字符串。現在看來,它包含一個數組。根據你想要做什麼,你可以用以下兩種方法之一重寫你的代碼。

您可以檢查test陣列中的任何字符串是否在line中。

if test.any? {|str| line.include?(str) } 
    # ... 
end 

,或者,如果你想確保所有在test的字符串必須包含在該行使用此

if test.all? {|str| line.include?(str) } 
    # ... 
end 
相關問題