Ruby Way Advanced data access

Source: Internet
Author: User

Often we need to store and get data in a more transparent way. The Marshal module provides a simple object persistence, and the Pstore library is built on this technology. The DBM Library is used as a hash and is permanently stored on disk.

1 Simple marshaling

Often we need to create an object and then save it for later use. Ruby provides basic support for this kind of object persistence (or marshaling). The Marshal module enables programmers to serialize and deserialize a Ruby object.

# array of elements [composer, work, minutes] works
= [[' Leonard Bernstein ', ' Overture to Candide ', one],
[Aa Ron Copland "," Symphony No. 3 ",
[" Jean Sibelius "," Finlandia ",]]
# We want to keep the this for later ...
File.Open ("Store", "W") do |file|
Marshal.dump (works,file)
end
# later ...
File.Open ("store") do |file|
Works = marshal.load (file) End

It should be noted here that not all objects can be dump. If an object contains an object of a lower class, he cannot be dump, such as IO, proc and binding, a single object, an anonymous object, or a module that cannot be serialized.

Marshal.dump also has the form of two other parameters, which, if passed in a parameter, will return a string representing the first two bytes of the primary and minor version numbers:

This way, the results of 1.9 and 1.8 are different:

s = marshal.dump (works)
P s[0] # 4
P s[1] # 8

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.