19
votes

In Ruby 1.9 you can have Fixnum, Float, and Symbol values that are unfrozen or frozen:

irb(main):001:0> a = [ 17, 42.0, :foo ]; a.map(&:frozen?)
=> [false, false, false]

irb(main):002:0> a.each(&:freeze); a.map(&:frozen?)
=> [true, true, true]

I understand the utility of freezing strings, arrays, or other mutable data types. As far as I know, however, Fixnum, Symbol, and Float instances are immutable from the start. Is there any reason to freeze them (or any reason that Ruby wouldn't report them as already frozen?

Note that in Ruby 2.0 Fixnums and Floats both start off as frozen, while Symbols retain the behavior described above. So, it's slowly getting 'better' :)

1

1 Answers

19
votes

The answer is no. Those data types are immutable. There is no reason to freeze those datatypes. The reason Ruby does not report those datatypes as frozen is because the obj.frozen? method returns the freeze status of the object and it is set to false initially for immutable datatypes. Calling obj.freeze will set the freeze status to true for that object.

The bottom line is that calling freeze on an immutable datatype sets the freeze status of the obj to true, but does nothing because the object is already immutable.