+ 2
Ruby - Why a can't be modified after freeze, but can be reassigned?
This will compile and outputs "1 2": a = [1,2,3] a.freeze a = [1,2] puts a
2 Answers
+ 3
Yes because you are creating a new object with the reference 'a'. The old 'a' is lost now. Isn't this concept almost the same in most of the languages?
You can verify it. I did a little research.
a = [1,2,3]
puts a.object_id #60
a.freeze
a = [1,2]
puts a.object_id #80
0
The freeze method is applied to an object reference, not a variable! This means that any operation that creates a new object will succeed.