Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file.each_line can only be called once

Tags:

iteration

ruby

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

like image 335
Kris Welsh Avatar asked Nov 18 '25 18:11

Kris Welsh


1 Answers

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"}
#=> ]
like image 118
Mulan Avatar answered Nov 21 '25 06:11

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!