user2016239
user2016239

Reputation:

ruby 2.0, why is #each_line mutating File object

I'm running irb as a one-off text preprocessing tool. I ran into immediate trouble just printing the text.

foo = File.open "bar"
foo.each_line {|l| puts l}

This prints as intended and returns #<File:emails plaintext>.

However, if I call #each_line again on the same object, no printing occurs, though it still returns #<File:emails plaintext>.

Why are the contents of the File object being overwritten by a call to #each_line? I thought the raison d'etre of #each-like methods was to ensure mutation does not occur. What is the proper 'ruby way' to do this?

Upvotes: 0

Views: 117

Answers (1)

Josh Lee
Josh Lee

Reputation: 177594

You have to rewind it: foo.rewind.

Consider how $stdin.each_line ought to behave. Since an IO object could be a file on disk, or it could be a stream or a pipe, it doesn’t make sense to guarantee that you can randomly seek around in it. Load it into an array if you want to iterate multiple times.

Upvotes: 3

Related Questions