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
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"}
#=> ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With