无法在Ruby中将StringIO转换为String(TypeError)

Vad*_*din 6 ruby zip open-uri

当我使用下面的代码时,我收到以下错误消息: 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
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?预先感谢.

jef*_*ias 22

您正在阅读的信息足够小,可以包含在stringIO对象中.通常发生的事情是,当数据太大(超过默认值10KB)时,对象被从缓冲区中取出并变成临时文件,您需要按照您尝试的方式读取它.

您有两种选择:
1.从较大的文件中读取
2.将openURI字符串缓冲区的默认值设置为0.

要设置默认缓冲区,您需要创建一个初始化程序并将其放入其中:

OpenURI::Buffer.send :remove_const, 'StringMax'
OpenURI::Buffer.const_set 'StringMax', 0
Run Code Online (Sandbox Code Playgroud)

第一行将删除当前缓冲区设置(10KB),第二行将其设置为0.

不要忘记重新启动服务器,因为它是初始化程序,否则什么都不会改变.我希望有所帮助!

  • 这救了我...使用Prawn来组合PDF并在生产中我会得到一个"无法将StringIO转换为字符串"错误.尝试了你的解决方案(即使没有直接相关),它解决了我的问题,如魔术. (2认同)

Den*_*hin 12

表达式open("URL for zipped file", "rb")返回StringIO,而不是String.

要获取StringIO的内容,必须调用方法 read

string = open(url).read()
Run Code Online (Sandbox Code Playgroud)