Ruby Freeze 方法在不同的对象上完成以下操作,基本上它是在 Ruby 中使对象保持不变或不可变。
- String
str = "this is string"
str.freeze
str.replace("this is new string") #=> FrozenError (can't modify frozen String)
or
str[0] #=> 't'
str[0] = 'X' #=> FrozenError (can't modify frozen String)
但您可以分配新字符串或更改其引用。一旦引用发生变化,它就不是冻结(或常量)对象。
str = "this is string"
str.freeze
str.frozen? #=> true
str = "this is new string"
str.frozen? #=> false
- 大批 :-
arr = ['a', 'b', 'c']
arr.freeze
arr << 'd' #=> FrozenError (can't modify frozen Array)
arr[0] = 'd' #=> FrozenError (can't modify frozen Array)
arr[1].replace('e') #=> ["a", "e", "c"]
arr.frozen? #=> true
arr 数组被冻结意味着您无法更改该数组。但数组内的字符串并未冻结。如果执行替换操作
在字符串“one”上,恶作剧地将其转换为“e”,当您重新检查(仍然冻结!)数组时,会显示该字符串的新内容。
- Hash
hash = {a: '1', b: '2'}
hash.freeze
hash[:c] = '3' #=> FrozenError (can't modify frozen Hash)
hash.replace({c: '3'}) #=> FrozenError (can't modify frozen Hash)
hash.merge({c: '3'}) #=> return new hash {:a=>"1", :b=>"2", :c=>"3"}
hash.merge!({c: '4'}) #=> FrozenError (can't modify frozen Hash)
hash.frozen? #=> true
hash = {:a=>"1", :b=>"2", :c=>"3"}
hash.frozen? #=> false
所以我们不能修改哈希内容,但我们可以将其引用到新的哈希(就像数组一样)