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