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

廉价感情. 提交于 2019-12-03 11:21:51

问题


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:


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.



来源:https://stackoverflow.com/questions/4235238/what-is-the-use-or-effect-of-freezing-symbols-and-numbers-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!