Freezing variables in Ruby doesn't work [duplicate] Freezing variables in Ruby doesn't work [duplicate] ruby ruby

Freezing variables in Ruby doesn't work [duplicate]


You freeze objects, not variables, i.e. you can't update a frozen object but you can assign a new object to the same variable. Consider this:

a = [1,2,3]a.freezea << 4# RuntimeError: can't modify frozen Array# `b` and `a` references the same frozen objectb = ab << 4    # RuntimeError: can't modify frozen Array# You can replace the object referenced by `a` with an unfrozen onea = [4, 5, 6]a << 7# => [4, 5, 6, 7]

As an aside: it is quite useless to freeze Fixnums, since they are immutable objects.


In Ruby, variables are references to objects. You freeze the object, not the variable.

Please note also that

a = [1, 2]a.freezea += [3]

is not an error because + for arrays creates a new object.


As mentioned in the other two answers, you freeze objects rather than variables.

I'd like to add a note on child objects, which aren't frozen when the parent is frozen. This can bite you hard if you don't pay attention to what you're doing, when exposing an object's internal structures:

class A  attr_accessor :varenda = A.newa.var = []a.freezea.var = []   # this fails as expecteda.var << :a  # this works, raises no errors, and no warnings

You can read about the rational here:

https://bugs.ruby-lang.org/issues/6037