3

I'm having some problems iterating through a file's lines, it seems like i can only use the each_line method once per file

file = open_file(path)
file.each_line { puts "Q"}
puts "--"
file.each_line { puts "Q"}
puts "--"
file.each_line { puts "Q"}
puts "--"
file.each_line { puts "Q"}

#Output: (on a file with three lines in it )
#Q
#Q
#Q
#--
#--
#--

it works fine with a regular iterator

3.times { puts "Q"}
puts "--"
3.times { puts "Q"}
puts "--"
3.times { puts "Q"}
puts "--"
3.times { puts "Q"}

#Output: (on a file with three lines in it )
#Q
#Q
#Q
#--
#Q
#Q
#Q
#--
#Q
#Q
#Q
#--
#Q
#Q
#Q

Is there anything i'm missing

Kris Welsh
  • 334
  • 2
  • 14

1 Answers1

6

You have to reset the file's read position using file#seek

Try this

file.each_line &method(:puts)
file.seek 0
file.each_line &method(:puts)

According to a comment, the following will work too

file.each_line &method(:puts)
file.rewind
file.each_line &method(:puts)

Dummie content

# users.json
[
  {"name": "bob"},
  {"name": "alice"}
]

Ruby

# output.rb
file = File.open("users.json")
file.each_line &method(:puts)

#=> [
#=>   {"name": "bob"},
#=>   {"name": "alice"}
#=> ]

file.seek 0
#=> 0

file.each_line &method(:puts)
#=> [
#=>   {"name": "bob"},
#=>   {"name": "alice"}
#=> ]
Mulan
  • 129,518
  • 31
  • 228
  • 259