如何将array.inspect的输出解析回数组 [英] How to parse output of array.inspect back into an array
问题描述
我想将多维数组存储在文本文件中并有效地重新加载它们.棘手的是,数组包含的字符串可能看起来像" ] , [ \\\""
或其他任何内容.
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.
将表写入文件的最简单方法就是my_array.inspect
(对吗?)
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)?
推荐答案
在我看来,这听起来太麻烦了.代替使用 YAML .
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')
作为替代方案,您可以改用 JSON .
As an alternative, you could use JSON instead.
这篇关于如何将array.inspect的输出解析回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!