有没有办法将字符串转换为文件,而不必将其写入磁盘? 我想通过一个字符串或者一个文件来普遍使用它:input = "123" if (ARGV.length == 1) input = File.open(ARGV[0]) #do stuff with input end 我可以从字符串创建一个文件吗(不写入磁盘)?否则,当它是一个字符串时,我将无法执行input.readline()。
您可以使用StringIO(1.8.7,1.9.3)来将字符串创建成一个像文件一样的IO(1.8.7,1.9.3)对象:file = StringIO.new("123") line = file.readline file.close
StringIO很好用,你也可以使用块来实现: StringIO.open(string) do |file| # do stuff here end 我更喜欢使用"alt"代替"file.close"
def hello_world(): print("Hello, world!") hello_world()
翻译:def hello_world(): print("你好,世界!") hello_world() end
- Alexey