?? 09 - avoiding boilerplate code with metaprogramming.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 + -