Home>

I am studying a reference book called "Introduction to Ruby for Professionals".
Therefore, I am doing iterative processing using the following module, but I am using each for array.
My understanding is that each does not use results and map wants to use results.
In this case, freeze processing is also required for the element, but it is a mystery that it is reflected in the original array_or_hash element even in the iterative processing using each.
Why is this using each?

Corresponding source code
module DeepFreezable
  def deep_freeze (array_or_hash)
    array_or_hash.each do | element |
      element.freeze
    end
    array_or_hash.freeze
  end
end
  • Answer # 1

    My understanding is that each does not use results and map wants to use results.

    This perception is different.mapCollects the results of the blocksNew arrayIs for making. The original array itselffreeze freezeIf you wantmapIt is inappropriate to create a new array with.

    It is a mystery that it is reflected in the original array_or_hash element even in the iterative process using each.

    .freezeAnd the object itselfDestructivelyIt has been changed.

Related articles