Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use or effect of freezing Symbols and Numbers in Ruby?

Tags:

ruby

ruby-1.9

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' :)

like image 970
Phrogz Avatar asked Nov 20 '10 22:11

Phrogz


People also ask

What does Ruby freeze do?

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.

What is the use of freeze rails?

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]".

What are symbols in Ruby?

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.

Can you freeze a hash in Ruby?

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.


1 Answers

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.

like image 78
Alex Avatar answered Sep 22 '22 23:09

Alex