14 - freezing an object to prevent changes.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 59 行

RB
59
字号
frozen_string = 'Brrrr!'frozen_string.freezefrozen_string.gsub('r', 'a')                      # => "Baaaa!"frozen_string.gsub!('r', 'a')# TypeError: can't modify frozen string#---sequences = [[1,2,3], [1,2,4], [1,4,9]].freezesequences << [2,3,5]# TypeError: can't modify frozen arraysequences[2] << 16                               # => [1, 4, 9, 16]#---frozen_string.clone.frozen?                      # => truefrozen_string.dup.frozen?                        # => false#---frozen_string = 'A new string.'frozen_string.frozen?                            # => false#---API_KEY = "100f7vo4gg".freezeAPI_KEY[0] = 4# TypeError: can't modify frozen stringAPI_KEY = "400f7vo4gg"# warning: already initialized constant API_KEY#---class MyClass  def my_method    puts "This is the only method allowed in MyClass."  end  MyClass.freezeendclass MyClass  def my_method    "I like this implementation of my_method better."  endend# TypeError: can't modify frozen classclass MyClass  def my_other_method    "Oops, I forgot to implement this method."  endend# TypeError: can't modify frozen classclass MySubclass < MyClass  def my_method    "This is only one of the methods available in MySubclass."  end  def my_other_method    "This is the other one."  endendMySubclass.new.my_method# => "This is only one of the methods available in MySubclass."#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?