How to serialize an array and deserialize back

后端 未结 2 541
既然无缘
既然无缘 2021-02-08 10:54

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 arra

相关标签:
2条回答
  • 2021-02-08 11:28

    Split is just a tool for chopping up strings - it doesn't know where that string came from.

    There are many ways of serialising data: YAML, JSON and Marshal being three that are part of the Ruby Standard Library. All distinguish between strings, integers and so on.

    There are pros and cons for each. For example, loading Marshal data from an untrusted source is dangerous and Marshal isn't good if you need to exchange the data with non-Ruby code. JSON is usually a good allrounder.

    0 讨论(0)
  • 2021-02-08 11:40

    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]
    
    0 讨论(0)
提交回复
热议问题