Ruby Convert String to File
Is it possible to convert a string to a file without writing it to disk?
I would like to work ubiquitously with either a string of a file:
input = "123"
if (ARGV.length == 1)
input = File.open(ARGV[0])
#do stuff with input
end
Can I create a file from a string (without writing to disk)? Otherwise, I would not be able to do 开发者_运维问答input.readline()
when it's a string.
You can use StringIO
(1.8.7, 1.9.3) to create an IO
(1.8.7, 1.9.3) object (that is, an object that acts like a file) out of a string:
file = StringIO.new("123")
line = file.readline
file.close
StringIO
can be used to give a file-like interface to strings.
The StringIO is nice, you could also do this using a block:
StringIO.open(string) do |file|
# do stuff here
end
I like this alt over file.close
精彩评论