What is the use or freeze effect of characters and numbers in Ruby?

In Ruby 1.9, you can have Fixnum , Float and Symbol values ​​that are thawed 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 usefulness of freezing strings, arrays, or other mutable data types. However, as far as I know, instances of Fixnum , Symbol and Float immutable from the start. Is there any reason to freeze them (or for some reason that Ruby will not report them as already frozen?

Note that in Ruby 2.0, Fixnum and Float both start as frozen, and Symbol retains the behavior described above. So, he slowly becomes "better" :)

+7
source share
1 answer

The answer is no. These data types are immutable. There is no reason to freeze these data types. The reason Ruby doesn't report these data types as frozen is because the obj.frozen? method obj.frozen? returns the freeze status of the object and sets to false initially for immutable data types. The obj.freeze call sets freeze true for this object.

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

+8
source share

All Articles