Skip to content

Instantly share code, notes, and snippets.

@v-yarotsky
Forked from anonymous/ruby_struct_marshal.rb
Last active December 10, 2015 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save v-yarotsky/4391138 to your computer and use it in GitHub Desktop.
Save v-yarotsky/4391138 to your computer and use it in GitHub Desktop.
WorkingExample before dump and load: #<WorkingExample:0x1076c37e0 @foo=1, @bar=2>
WorkingExample dumpU:WorkingExamplei
WorkingExample after dump and load: #<WorkingExample:0x1076c33d0 @foo=1>
FaultyExample before dump and load: @foo=,@bar=,@qux=3
FaultyExample dumpIU:FaultyExamplei
FaultyExample after dump and load: @foo=1,@bar=,@qux=
WorkingExample before dump and load: #<WorkingExample:0x007fa18209ca88 @bar=2, @foo=1>
WorkingExample dumpU:WorkingExamplei
WorkingExample after dump and load: #<WorkingExample:0x007fa18209c830 @foo=1>
FaultyExample before dump and load: @foo=,@bar=,@qux=3
FaultyExample dumpIU:FaultyExamplei: @quxi
FaultyExample after dump and load: @foo=1,@bar=,@qux=3
class WorkingExample
def initialize
@foo = 1
@bar = 2
end
def marshal_dump
@foo
end
def marshal_load(foo)
@foo = foo
end
end
class FaultyExample < Struct.new(:foo, :bar)
def initialize
super(1, 2)
@qux = 3
end
def marshal_dump
foo
end
def marshal_load(foo)
@foo = foo
end
def inspect
"@foo=#@foo, @bar=#@bar, @qux=#@qux"
end
end
a = WorkingExample.new
puts "WorkingExample before dump and load: #{a.inspect}"
puts "WorkingExample dump #{Marshal.dump(a)}"
puts "WorkingExample after dump and load: #{Marshal.load(Marshal.dump(a)).inspect}"
puts
b = FaultyExample.new
puts "FaultyExample before dump and load: #{b.inspect}"
puts "FaultyExample dump #{Marshal.dump(b)}"
puts "FaultyExample after dump and load: #{Marshal.load(Marshal.dump(b)).inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment