如何将对象保存到文件中?
我想将对象保存到文件中,然后轻松地从文件中读取它。举一个简单的例子,假设我有以下 3d 数组:
m = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]
是否有一个简单的 Ruby API 可以用来实现此目的,而无需编写解析器来解释文件中的数据?在我给出的示例中,这很简单,但是随着对象变得更加复杂,使对象持久化会变得很烦人。
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:
m = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]
Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
YAML 和 Marshal 是最明显的答案,但根据您计划如何处理数据,sqlite3 也可能是一个有用的选项。
YAML and Marshal are the most obvious answers, but depending on what you're planning to do with the data, sqlite3 may be a useful option too.
您需要先序列化对象,然后才能将它们保存到文件并反序列化它们以检索它们。正如 Cory 提到的,有 2 个标准序列化库被广泛使用,
Marshal
和YAML
。Marshal
和YAML
分别使用dump
和load
方法进行序列化和反序列化。以下是如何使用它们:
您需要注意文件大小以及与文件读/写相关的其他问题。
更多信息当然可以在 API 文档中找到。
You need to serialize the objects before you could save them to a file and deserialize them to retrieve them back. As mentioned by Cory, 2 standard serialization libraries are widely used,
Marshal
andYAML
.Both
Marshal
andYAML
use the methodsdump
andload
for serializing and deserializing respectively.Here is how you could use them:
You need to be careful about the file size and other quirks associated with File reading / writing.
More info, can of course be found in the API documentation.
请参阅元帅:http://ruby-doc.org/core/classes/Marshal.html< /a>
-或-
YAML: http://www.ruby-doc.org /core/classes/YAML.html
See Marshal: http://ruby-doc.org/core/classes/Marshal.html
-or-
YAML: http://www.ruby-doc.org/core/classes/YAML.html