I'm saving a SortedSet object in a file using Marshal.dump. The elements in the set are objects as well (that include Comparable and implement the <=> method).
Later on when restoring that object using Marshal.load, the SortedSet that is loaded from the file is not sorted...
Any idea why or how to fix it?
Here is a simplified example that reproduce the problem:
require 'set'
class Foo
include Comparable
attr_accessor :num
def initialize(num)
@num = num
end
def <=>(other)
num <=> other.num
end
end
f1 = Foo.new(1)
f2 = Foo.new(2)
f3 = Foo.new(3)
s = SortedSet.new([f2, f1, f3])
File.open('set_test.dump', 'wb') { |f| Marshal.dump(s, f) }
Than, to load the object from the file i use -
File.open('set_test.dump', 'rb') { |f| ls = Marshal.load(f) }
** I'm using Rails 3.2.3 with Ruby 2.1.8
** When loading the dump from the file - do it in a new/seperate rails console (and don't forget to copy-paste the definition of the Foo class :-) )
File.open('set_test.dump', 'rb') { |f| ls = Marshal.load(f) }
can also be writtenMarshal.load(File.binread('set_test.dump'))
.Marshal
. And he is right. When dumping using Marshal with a specific Ruby version, It might not load properly with a different Ruby version.