09 - avoiding boilerplate code with metaprogramming.rb

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

RB
59
字号
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 + =
减小字号Ctrl + -
显示快捷键?