2015-10-13 59 views
0

我正在嘗試讀取文件名並處理每一行。如何將文件名傳遞給函數?通過將文件傳遞給函數來讀取文件

puts "file name?? " 
_file = get.chomps 

def printFile(_file) 
    do |f| 
    f.each_line do |line| 
     print_me = "Line 1 " + line 
     return print_me 
    end 
    end 
end 

我打算通過print_me像另一個功能:

def thisWillPrint(print_me) 
    new_print = print_me + " DONE! " 
end 

回答

1

我可以看到代碼中的一些問題。首先,您在printFile函數的定義中使用了一個塊,這是一個語法錯誤,接下來使用該塊中從未給出值的變量f,除此之外,您嘗試對其執行循環並且從不打開一個文件描述符。最後,你必須在某處調用printFile函數,以便Ruby知道它必須運行它。

你的printFile函數應該做的第一件事是獲得一個file descriptor作爲一個字符串在_file變量的用戶給你的文件,這樣你實際上有一個流,你可以從字符串對象讀取的線。因此,我建議您將變量從_file更改爲fileName,並將文件保留爲流。你可以通過使用Ruby自己的File類來調用它,並調用它的open方法。正如你可以從文檔中看到的,可以用幾種不同的方式調用open,但是讓我們用你想要做的一個塊。

puts 'give me a path to a file' 
fileName = gets.chomp 

def printFile(fileName) 
    counter = 0 
    File.open(fileName) do |file| 
    while line = file.gets 
     print_me = "line " + counter.to_s + " "+line 
     thisWillPrint(print_me) 
    end 
    end 
end 

def thisWillPrint(print_me) 
    puts print_me + " DONE! " 
end 

printFile(fileName) 

您還必須在最後調用printFile函數,以便ruby實際運行某些內容。

0

注意,通過內環路返回,你將退出它。通過以下內容,您將獲得文件的內容。

def printfile(filename) 
     print_me = "" 
     File.open(filename, "r") do |f| 
     f.each {|line| print_me << line } 
     end 
     print_me 
    end 

對於大文件,返回變量也會非常大。

0

要從標準輸入讀取一行,可以使用gets方法。默認情況下,gets方法會捕獲換行符\n。您必須使用chomp方法來消除換行符。

所以從標準輸入獲得文件的名稱,你可以做到以下幾點:

print "File's name? " 
_file = gets.chomp 

裏面的printFile方法,你可以做到以下幾點:

def printFile(_file) 
    print_me = "" 
    File.foreach(_file) do |line| 
    # process each line however you'd like inside this block 
    # for example: 
    print_me += line 
    end 
    return print_me # explicit return not required 
end 

注意,您不必如果它是方法中的最後一個表達式,則表示'返回'某種東西。最後一個表達式可能只是print_me

你可以通過什麼這個方法返回的另一種方法像thisWillPrint這樣的:

def thisWillPrint(print_me) 
    new_print = print_me + "Done!" 
end 

output = printFile(_file) 
thisWillPrint(output) 
相關問題