Maria Shilva
Maria Shilva

Reputation: 81

Printing lines from a file in ruby

When I start printing lines from a file, I get this error

#<File:0x007ff65ee297b0>

Here is the code

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

Upvotes: 0

Views: 58

Answers (4)

Aur&#233;lien Bottazini
Aur&#233;lien Bottazini

Reputation: 3309

This is not an error. It prints correctly one line which is your File object. Here your create a file object and you did not ask it to fetch lines or anything else for that matter.

Several good answers already. But here is another way to do it with minimal change to your code:

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

Upvotes: 2

Patrick Oscity
Patrick Oscity

Reputation: 54674

You are printing the file object. To get the contents line by line, you can use File.foreach

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

To process the whole file at once, you can use the read method on the file object:

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

Upvotes: 4

tihom
tihom

Reputation: 8003

Another way :

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

Or

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

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

File::open returns file handle (which apparently is being printed out as #<File:0x007ff65ee297b0>.) If you need the file content line by line you might want to use IO::readlines:

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

Upvotes: 1

Related Questions