file.each_line can only be called once

iteration, ruby

Solution

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"}
#=> ]

Problem

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

Original source