⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 14 - freezing an object to prevent changes.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -