Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Ruby Cookbook | メタプログラミングでコードのボイラープレートを避ける

パンくず

Ruby Cookbook
メタプログラミングでコードのボイラープレートを避ける

概要

メタプログラミングでコードのボイラープレートを避ける

内容

メソッド名・処理内容がメソッドがある場合は、
define_methodによるメタプログラミングで簡潔に記載可能です。

サンプルコード

# encoding: Windows-31J
require "pp"

class Hoge
  def print_hxge(word)
    puts "h#{word}ge"
  end
  def hage
    print_hxge("a")
  end

  def hige
    print_hxge("i")
  end

  def huge
   print_hxge("u")
  end
  
    def hege
   print_hxge("e")
  end

  def hoge
   print_hxge("o")
  end
end

hoge = Hoge.new
hoge.hage
hoge.hige
hoge.huge
hoge.hege
hoge.hoge

class HyperHoge
  def print_hxge(word)
    puts "h#{word}ge"
  end

  %w{a i u e o}.each {|word|define_method("h#{word}ge") {print_hxge(word)}}
end

hyper_hoge = HyperHoge.new
puts "methods = #{hyper_hoge.public_methods(false)}"

hyper_hoge.public_methods(false).each do |method_|
  each_method = hyper_hoge.method(method_)
  (each_method.arity == 1) ? each_method.call("x"):each_method.call
end

出力

hage
hige
huge
hege
hoge
methods = [:print_hxge, :hage, :hige, :huge, :hege, :hoge]
hxge
hage
hige
huge
hege
hoge