+ 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

11th Nov 2020, 12:37 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
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
11th Nov 2020, 1:58 PM
Avinesh
Avinesh - avatar
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.
11th Nov 2020, 1:57 PM
Nataliya
Nataliya - avatar