ruby way之進階資料存取

來源:互聯網
上載者:User

經常我們需要以一種更透明的方式來儲存和得到資料.Marshal模組提供了簡單的對象持久化,PStore 庫建立在這項技術之上。dbm 庫使用像hash一樣並永久的存貯在磁碟上.

1簡單的Marshaling

經常我們需要建立一個對象,然後為了以後的使用儲存它.ruby對這種對象持久化(或者說是 Marshaling)提供了基本的支援.Marshal 模組能夠使程式員序列化和還原序列化一個ruby對象.

# array of elements [composer, work, minutes]  works = [["Leonard Bernstein","Overture to Candide",11],     ["Aaron Copland","Symphony No. 3",45],     ["Jean Sibelius","Finlandia",20]]# We want to keep this for later...File.open("store","w") do |file| Marshal.dump(works,file)end # Much later...File.open("store") do |file| works = Marshal.load(file)end

這裡要注意的是這種技術並不是所有的對象能被dump.如果一個對象包含一個低層級的類的對象,他就 不能被dump,比如IO、Proc和Binding,單例對象,匿名對象,模組也不能被序列化.

Marshal.dump 還有另外兩種參數的形式,如果調用時傳入一個參數的話,它將會返回返回一個由字元 串表示的資料,其中前兩個位元組為主要版本號和次版本號碼:

這邊的話1.9和1.8的結果是不同的:

s = Marshal.dump(works) p s[0] # 4 p s[1] # 8

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.