Can't convert StringIO into String (TypeError) in Ruby

Vadim Baldin picture Vadim Baldin · Nov 9, 2012 · Viewed 9.4k times · Source

When I use the code below, I get the following error message: can't convert StringIO into String (TypeError)

array_of_lines = []
Zip::ZipInputStream::open(open("URL for zipped file", "rb")) do |io|
  file = io.get_next_entry
  puts "Downloading file #{file}"
  array_of_lines = io.readlines
  print "Downloaded ", array_of_lines.count, " elements.", "\n"
end

Can someone help me? Thank in advance.

Answer

jeffreymatthias picture jeffreymatthias · Dec 11, 2012

The information you're reading is small enough that it can be contained in a stringIO object. What normally happens is that as the data gets too large (over the default of 10KB) the object is taken out of the buffer and turned into a temp file, which you need to be to read it the way that you're trying to.

You have two options:
1. read from larger files
2. set the default for the openURI string buffer to 0.

To set the default buffer, you need to create an initializer and put this in it:

OpenURI::Buffer.send :remove_const, 'StringMax'
OpenURI::Buffer.const_set 'StringMax', 0

The first line will delete the current buffer setting (10KB) and the second line will set it to 0.

Don't forget to restart your server since it's an initializer or nothing will change. I hope that helps!