Leon's Blogging

Coding blogging for hackers.

Ruby - 用 Marshal 來傳遞資料

| Comments

當兩台 server 要互相傳遞資料時,都必須確保資料的正確性,因此可以透過 Marshal 解析後來傳遞。

一般可以用 to_a, to_yml, to_s 來轉成不同 type 但這樣很可能會失真

因此用 Marshal 就會比較精準,並且快很多

1
2
3
4
5
6
7
8
9
10
h = {:a=>1, "b"=>2, Time.new=>Class}

Marshal.dump(h)
#=> "\x04\b{\b:\x06ai\x06I\"\x06b\x06:\x06ETi\aIu:\tTime\r\xE7\x04\x1D\x80r\xB6D\xC0\a:\voffseti\x02\x80p:\tzoneI\"\bCST\x06;\x06Fc\nClass"

File.open("test.txt", "w").write(Marshal.dump(h))

#在 irb 要先 exit 重開
Marshal.load(File.open("test.txt", "r").read)
#=> {:a=>1, "b"=>2, Time.new=>Class}

官方文件:

Comments