Search code examples
ruby-on-railsrubyopenstruct

Why do OpenStruct values change when a hash with its dumped values change?


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!


Solution

  • 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}