Tbpgr Blog

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

メタプログラミングRuby | 魔術 | 動的ディスパッチ

概要

動的ディスパッチ

内容

実行時に呼び出すメソッドを決めます。
メソッドを直接呼び出さずsendを利用します。

サンプル

ゴーストメソッドと組み合わせてみました。
0-10の乱数を2倍にして返却する
methodXをゴーストメソッドとして定義します。
※Xは0-10の数値

# encoding: utf-8
require "pp"

class DynamicDispatch
  def random_call
    self.send "method#{rand(10).to_s}".to_sym
  end

  def method_missing(method_name, *args, &block)
    singleton_class.class_eval do
      define_method method_name.to_s do
        puts method_name.to_s.gsub(/method/, '').to_i*2
      end.call
    end
  end
end

d = DynamicDispatch.new
10.times {d.random_call}

puts "@@@@@@@@@@@@@@@@@@@@@@"
d.method1
実行結果
14
8
10
16
2
14
2
6
14
14
@@@@@@@@@@@@@@@@@@@@@@
2