如何序列化数组并反序列化 [英] How to serialize an array and deserialize back

查看:268
本文介绍了如何序列化数组并反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何序列化数组并从字符串反序列化?我尝试了以下代码,但它并没有真正返回整数的原始数组,而是为字符串数组返回了。

How do I serialize an array and deserialize it back from a string? I tried the following code, but it doesn't really return the original array of integers but does for the array of strings.

 x = [1,2,3].join(',') # maybe this is not the correct way to serialize to string?
 => '1,2,3'

 x = x.split(',')
 => [ '1', '2', '3' ]

有没有办法找回它到没有 .collect {| x |的整数x.to_i}

Is there a way to get it back to integers without having the .collect{ |x| x.to_i }?

推荐答案

标准方法是使用 Marshal

x = Marshal.dump([1, 2, 3])
#=> "\x04\b[\bi\x06i\ai\b"

Marshal.load(x)
#=> [1, 2, 3]

但是您也可以使用 JSON实现

require 'json'

x = [1, 2, 3].to_json
#=> "[1,2,3]"

JSON::parse(x)
#=> [1, 2, 3]

YAML

require 'yaml'

x = [1, 2, 3].to_yaml
#=> "---\n- 1\n- 2\n- 3\n"

YAML.load(x)
#=> [1, 2, 3]

这篇关于如何序列化数组并反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆