How to serialize an array and deserialize back

deserialization, ruby, serialization

Solution

The standard way is with `Marshal`:

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

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

But you can also do it with `JSON`:

require 'json'

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

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

Or `YAML`:

require 'yaml'

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

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

Problem

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' ] ``` Is there a way to get it back to integers without having the `.collect{ |x| x.to_i }`?

Original source