Mahoni
Mahoni

Reputation: 7466

Make StringIO applicable for IO.foreach

I would like to make the following lines work:

input = StringIO.new
input.write("test\ntest2")
IO.foreach(input) { |line| … }

I know that IO.foreach takes a file description. Can I turn that into a file descriptor or fake it, make it work in a different way?

Upvotes: 0

Views: 307

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

To read from a StringIO after you've written to it, you need to roll it back to the beginning, using seek:

input = StringIO.new
input.write("test\ntest2")
input.seek(0)
input.each_line { |x| p x }
# "test\n"
# "test2"

Upvotes: 1

Related Questions