Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Convert String to File

Tags:

string

file

ruby

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.

like image 448
Verhogen Avatar asked Jan 19 '10 14:01

Verhogen


3 Answers

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
like image 131
Brian Campbell Avatar answered Oct 06 '22 18:10

Brian Campbell


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

like image 5
Brian Young Avatar answered Oct 06 '22 16:10

Brian Young


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

like image 2
shicholas Avatar answered Oct 06 '22 16:10

shicholas