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 Fixnum
s and Float
s both start off as frozen, while Symbol
s retain the behavior described above. So, it's slowly getting 'better' :)
The freeze method in Ruby is used to ensure that an object cannot be modified. This method is a great way to create immutable objects. Any attempt to modify an object that has called the freeze method will result in the program throwing a runtime error.
By using #freeze, I'm able to create a constant that's actually constant. This time, when I attempt to modify the string, I get a RuntimeError. Here' a real-world example of this in the ActionDispatch codebase. Rails hides sensitive data in logs by replacing it with the text "[FILTERED]".
Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.
You can always freeze your hashes in Ruby for safety if you want to. All that's missing is some sugar for declaring immutable hash literals.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With