Feature #17627
openSuggestion: Implement `freeze_values` instance method on collection-like classes.
Description
Suggestion: Implement freeze_values
instance method on collection-like classes.
By collection-like classes, I mean classes such as Array, Hash, Set, Struct, OpenStruct, and custom classes containing multiple objects.
There has been some discussion of a recursive deep_freeze
method, and although it could be very useful, there are potential problems regarding unintended consequences, and guarding against these would make the implementation more complex.
This complexity could be greatly reduced if we limit the scope of the freeze to only one level, and have the new freeze_values
method call freeze
.
The implementation would be trivial, I think. For example:
class Array # same for Set
def freeze_values
each(&:freeze)
end
end
class Hash
def freeze_values
values.each(&:freeze)
end
end
There would still be a risk that the programmer would call this when some values should not be frozen, but that risk would be smaller and more manageable.
Also, there are many cases in which these collections contain simple objects such as strings and numbers. In these cases, recursion would not be necessary or helpful.
Although it could be argued that the implementation is so trivial that it does not need a method implemented, I believe that:
- the method would nevertheless simplify the task, encouraging freezing
- the method name would be a higher level description of the operation, making the code more readable
- custom classes could implement this contract in their own way, yielding the benefits of polymorphism
What do you think?