1

I'd like to know what's happening.

When I do the following:

new_struct = OpenStruct.new()
new_struct.color = 'Red'
new_struct.number = 4

This results in:

#<OpenStruct color="Red", number=4>

If I then create and change some params:

params = { first: new_struct.marshal_dump }

params[:first][:color] = 'Orange'

This results in the OpenStruct changing to:

#<OpenStruct color="Orange", number=4>

Why does this OpenStruct change if I change the params hash? And is there a way to change the params hash without changing the OpenStruct?

Thanks!

Lee
  • 601
  • 9
  • 21

2 Answers2

2

It's not that suprising, marshal_dump returns the hash with the namespace of the OpenStruct object, which is mutable like any other hash. If you want to prevent this behavior, clone it:

params = {first: new_struct.marshal_dump.clone}
tokland
  • 66,169
  • 13
  • 144
  • 170
  • Thanks, I figured there had to be some reason. The OpenStruct was one of the columns in my db and it surprised me that it was changing. – Lee Aug 28 '12 at 21:24
1

From the marshal_dump() entry for OpenStruct on ruby-doc:

Provides marshalling support for use by the Marshal library. Returning the underlying Hash table that contains the functions defined as the keys and the values assigned to them.

The hash you get from marshal_dump() is actually the underlying representation of the OpenStruct, so any changes in the hash will be reflected in the object. You could always clone the hash to get around this.

Pete Schlette
  • 1,948
  • 1
  • 13
  • 18