如何将 IO 对象转换为 Ruby 中的字符串?

问题描述 投票:0回答:3

我正在使用 IO 对象(一些

STDOUT
输出文本),并且我正在尝试将其转换为字符串,以便我可以进行一些文本处理。我想做这样的事情:

my_io_object = $stdout
#=> #<IO:<STDOUT>>

my_io_object.puts('hi')  #note: I know how to make 'hi' into a string, but this is a simplified example
#=>hi

my_io_object.to_s

我尝试了一些方法并遇到了一些错误:

my_io_object.read 
#=> IOError: not opened for reading

my_io_object.open
#=> NoMethodError: private method `open' called for #<IO:<STDOUT>>

IO.read(my_io_object)
#=> TypeError: can't convert IO into String

我已经通读了 IO 类方法,但我不知道如何操作该对象中的数据。有什么建议吗?

ruby io
3个回答
38
投票

我通过将输出定向到 StringIO 对象而不是 STDOUT 来解决这个问题:

> output = StringIO.new
#<StringIO:0x007fcb28629030>
> output.puts('hi')
nil
> output.string
"hi\n"

0
投票
 # Open a new file in write mode
 File.open(filename, 'wb') do |file|
   # Write data from io.string to the file
   file.write(io.string)
 end
  1. File.open(filename, 'wb') 使用指定的文件名打开一个新文件 写入模式下的文件名('wb'表示二进制写入模式,即 适用于写入 Excel 文件等二进制数据)。

  2. 在块内,file.write(io.string) 写入数据 io.string 到文件中。

  3. 最后,当块退出时文件会自动关闭。


-1
投票

STDOUT
接受字符串,但不提供字符串。您可以对其进行写入,但无法从中读取。

STDOUT.write("hello") # => hello
STDOUT.read # => IOError: not opened for reading
© www.soinside.com 2019 - 2024. All rights reserved.