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 Fixnum
s, since they are immutable objects.
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: