As with YAML serialization, it is possible to limit the variables that are saved when serializing using Marshal. In YAML, you did this by writing a method called to_yaml_properties
. With Marshal, you need to write a method named marshal_dump
. In the code of this method you should create an array containing the actual variables to be saved (in YAML, you created an array of strings containing the variable names).
This is an example:
def marshal_dump [@variable_a, @variable_b] end
Another difference is that, with YAML, you were able simply to load the data in order to re-create an object. With Marshal, you need to add a special method called marshal_load
to which any loaded data is passed as an argument. This will be invoked automatically when you call Marshal.load
, and it will be passed the data in the form of an array. The previously saved objects can be parsed from this array. You can also assign values to any variables that were omitted (such as @some_other_variable
here) when the data was saved:
def marshal_load(data) @variable_a = data[0] @variable_b = data[1] @some_other_variable = "a default value" end
Here is a complete program that saves and restores the variables @num
and @arr
but omits @str
:
limit_m.rb
class Mclass def initialize(aNum, aStr, anArray) @num = aNum @str = aStr @arr = anArray end def marshal_dump [@num, @arr] end def marshal_load(data) @num = data[0] @arr = data[1] @str = "default" end end ob = Mclass.new( 100, "fred", [1,2,3] ) p( ob ) #=> #<Mclass:0x2be7278 @num=100, @str="fred", @arr=[1, 2, 3]> marshal_data = Marshal.dump( ob ) ob2 = Marshal.load( marshal_data ) p( ob2 ) #=> #<Mclass:0x2be70e0 @num=100, @str="default", @arr=[1, 2, 3]>
Note that although the serialization is done here in memory, the same techniques can be used when using Marshal to save and load objects to and from disk.