2

I want to store multidimensional arrays in text files and reload them efficiently. The tricky part is that the array includes strings which could look like " ] , [ \\\"" or anything.

Easiest way of writing the table to file is just as my_array.inspect (right?)

How do I then recreate the array as quickly and painlessly as possible from a string read back from the text file that might look like "[\" ] , [ \\\\\\\"\"]" (as in the above case)?

1
  • 2
    It might help if you could post an example of your text file so we can see exactly what you're trying to accomplish. Commented Jun 23, 2011 at 13:59

3 Answers 3

4

If your array only includes objects that are literally written such as Numerals, Strings, Arrays, Hashes, you can use eval.

a = [1, 2, 3].inspect
# => "[1, 2, 3]"

eval(a)
# => [1, 2, 3]
Sign up to request clarification or add additional context in comments.

3 Comments

That's exactly what I wanted to know. Although I went with the YAML option anyway.
eval() is evil and it's slow. Just saying.
I agree with Kudu, eval() is the wrong approach. Use plaintext (Yaml, JSON) or binary (Marshal) but be very careful relying on executing arbitrary Ruby code as a form of serialization.
2

In my opinion, this sounds like too much trouble. Use YAML instead.

require 'yaml'
a = [ [ [], [] ], [ [], [] ] ]
File.open("output.yml", "w") do |f|
  f.write a.to_yaml
end
b = YAML.load File.open('output.yml', 'r')

As an alternative, you could use JSON instead.

Comments

0

Say you have array

ary

You could write the array to a file:

File.open(path, 'w') { |f| f.write Marshal.dump(ary) }

and then re-create the array by reading the file into a string and saying

ary = Marshal.load(File.read(path))

3 Comments

Interesting solution, but binary serialization has it's own set of issues. I try to avoid Marshal / pickle in production, resorting instead to YAML or JSON.
If you want a plaintext serialization format, you might want to use the yajl-ruby gem... they say it's even faster than Marshal... replace "Marshal.dump" with "Yajl::Encoder.encode" and "Marshal.load" with "Yajl::Parser.parse"
Nat, binary serialization is tricky and works for one programming language only. With YAML or JSON, you can load the array into Ruby, Python, C, etc. Also, if something doesn't work the way it should, you can look at the text file to debug it, instead of parsing the binary data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.