Project

General

Profile

Actions

Feature #17627

open

Suggestion: Implement `freeze_values` instance method on collection-like classes.

Added by keithrbennett (Keith Bennett) about 3 years ago. Updated about 3 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:102481]

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:

  1. the method would nevertheless simplify the task, encouraging freezing
  2. the method name would be a higher level description of the operation, making the code more readable
  3. custom classes could implement this contract in their own way, yielding the benefits of polymorphism

What do you think?

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0