Skip to content

Instantly share code, notes, and snippets.

@tjkendev
Last active September 30, 2017 19:20
Show Gist options
  • Save tjkendev/56270417c408fabfae23b8653aa3e32e to your computer and use it in GitHub Desktop.
Save tjkendev/56270417c408fabfae23b8653aa3e32e to your computer and use it in GitHub Desktop.
メタプログラミング
  • オープンクラス
class String
  def hello
    'hello'
  end
end
"a".hello # => 'hello'
class D
  def a; end
end
class D
  def b; end
end
  • 動的メソッド
# 動的ディスパッチ
class MyClass
  def m1(a)
    a**2
  end
end

obj = MyClass.new
obj.m1(3)        # => 9
obj.send(:m1, 3) # => 9

# 動的メソッド
class MyClass
  define_method :m2 do |a|
    a**2
  end
end

obj = MyClass.new
obj.m2(3) # => 9
  • ゴーストメソッド
class MyClass
  def get_hello(name)
    "hello, #{name}"
  end
  def method_missing(name, *args, &block)
    super if !respond_to?("get_#{name}")
    send("get_#{name}", *args)
  end
end

obj = MyClass.new
obj.hello("world") # => "hello, world"
  • 特異メソッド
# 特異メソッド
a = "abcde"
def a.head
  self[0]
end
a.head # => "a"

# クラスメソッド(クラスの特異メソッド)
def MyClass.m1; end

class << MyClass # 特異クラスを覗く
  def m2; end
end

class MyClass
  class << self # 特異クラスを覗く
    def m3; end
  end
end

====

参考: メタプログラミングRuby

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment