How to unfreeze the Hash?

Viewed 1135

I have an object from GraphQL. I need to process one field and then return a Hash.

To do this I initially tried using the to_h method. But when I tried to change the value in the field, I got this error:

FrozenError - can't modify frozen Hash

Then I came up with the idea of using the dup method. This method seems to "unfreeze" the original object:

object.to_h.dup

But this doesn't help for "deep" fields. For "deep" fields I had to use the local dup method.

Please tell me if there is a more correct solution to the problem?

1 Answers

Rails (or ActiveSupport if you want to be pedantic) patches a deep_dup method into Hash which does a deep copy. So you should be able to say:

object.to_h.deep_dup

to get a fully mutable version of your Hash.

Related