将Ruby字符串转换为文件

14

有没有办法将字符串转换为文件,而不必将其写入磁盘?

我想通过一个字符串或者一个文件来普遍使用它:

input = "123"
if (ARGV.length == 1)
   input = File.open(ARGV[0])

   #do stuff with input
end

我可以从字符串创建一个文件吗(不写入磁盘)?否则,当它是一个字符串时,我将无法执行input.readline()


请在示例结尾处添加end关键字 ;)Example:def hello_world(): print("Hello, world!") hello_world()翻译:def hello_world(): print("你好,世界!") hello_world() end - Alexey
3个回答

36

您可以使用StringIO1.8.71.9.3)来将字符串创建成一个像文件一样的IO1.8.71.9.3)对象:

file = StringIO.new("123")
line = file.readline
file.close

5

StringIO可以用来为字符串提供类似文件的接口。


2

StringIO很好用,你也可以使用块来实现:

StringIO.open(string) do |file|
  # do stuff here
end

我更喜欢使用"alt"代替"file.close"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接