在 Ruby 中冻结符号和数字的用途或效果是什么? [英] What is the use or effect of freezing Symbols and Numbers in Ruby?
问题描述
在 Ruby 1.9 中,您可以拥有未冻结或冻结的 Fixnum
、Float
和 Symbol
值:
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]
我了解冻结字符串、数组或其他可变数据类型的实用性.然而,据我所知,Fixnum
、Symbol
和 Float
实例从一开始就是不可变的.是否有任何理由冻结它们(或者 Ruby 不会将它们报告为已经 frozen 的任何原因?
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?
请注意,在 Ruby 2.0 中 Fixnum
s 和 Float
s 都以冻结开始,而 Symbol
s 保留所描述的行为以上.所以,它正在慢慢变得更好":)
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' :)
推荐答案
答案是否定的.这些数据类型是不可变的.没有理由冻结这些数据类型.Ruby 没有将这些数据类型报告为冻结的原因是因为 obj.frozen?
方法返回对象的冻结状态,对于不可变数据类型,它最初设置为 false
.调用 obj.freeze
会将 freeze
状态设置为该对象的 true
.
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.
最重要的是,在不可变数据类型上调用 freeze
会将 obj 的 freeze
状态设置为 true
,但什么也不做,因为对象已经是不可变的.
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.
这篇关于在 Ruby 中冻结符号和数字的用途或效果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!