14

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.

| |
  • please add end keyword at the end of your example ;) – Alexey May 5 '10 at 21:15
35

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
| |
5

StringIO can be used to give a file-like interface to strings.

| |
2

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

| |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.