2014-11-04 168 views
0

當我開始打印線從一個文件,我得到這個錯誤印刷線紅寶石

#<File:0x007ff65ee297b0> 

這裏是代碼

require 'rubygems' 
File.open("sample.txt", 'r') do |f| 
puts f 
end 
+3

這不是錯誤。它正在打印文件對象 – tihom 2014-11-04 07:36:12

+1

你的問題是什麼? – sawa 2014-11-04 08:04:04

回答

1

另一種方式:

IO.foreach("sample.txt") {|line| line } 

或者

File.foreach('sample.txt') {|line| line } 
1

File::open返回文件句柄(這顯然正在打印爲#<File:0x007ff65ee297b0>。)如果您需要逐行輸入文件內容,您可能需要使用IO::readlines

IO.readlines("sample.txt").each do |line| 
    puts line 
end 
4

您要打印的文件對象。要獲得通過線的內容線,您可以使用File.foreach

File.foreach('sample.txt', 'r') do |line| 
    puts line # called for every line 
end 

要處理整個文件一次,你可以使用read方法的文件對象:

File.open('sample.txt', 'r') do |file| 
    puts file.read # called only once 
end 
2

這不是一個錯誤。它正確打印一行是你的File對象。 在這裏你創建一個文件對象,你沒有要求它獲取線或其他任何事情。

已經有幾個很好的答案。但這裏有另一種方法,只需對代碼進行最小限度的更改:

File.open("sample.txt", 'r').each_line do |f| 
    puts f 
end