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

📄 09 - avoiding boilerplate code with metaprogramming.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
class Fetcher  def fetch(how_many)    puts "Fetching #{how_many ? how_many : "all"}."  end  def fetch_one    fetch(1)  end  def fetch_ten   fetch(10)  end  def fetch_all    fetch(nil)  endend#---class GeneratedFetcher  def fetch(how_many)    puts "Fetching #{how_many ? how_many : "all"}."  end  [['one', 1], ['ten', 10], ['all', nil]].each do |name, number|    define_method("fetch_#{name}") do      fetch(number)    end  endendGeneratedFetcher.instance_methods - Object.instance_methods# => ["fetch_one", "fetch", "fetch_ten", "fetch_all"]GeneratedFetcher.new.fetch_one# Fetching 1.GeneratedFetcher.new.fetch_all# Fetching all.#---class Numeric  [['add', '+'], ['subtract', '-'], ['multiply', '*',],   ['divide', '/']].each do |method, operator|    define_method("#{method}_2") do      method(operator).call(2)    end  endend4.add_2                                           # => 610.divide_2                                       # => 5#---define_method 'call_with_args' do |*args, &block|  block.call(*args)endcall_with_args(1, 2) { |n1, n2| n1 + n2 }                    # => 3call_with_args 'mammoth' { |x| x.upcase }                    # => "MAMMOTH"#---

⌨️ 快捷键说明

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