Tbpgr Blog

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

メタプログラミングRuby | 魔術 | オブジェクト拡張

概要

オブジェクト拡張

内容

オブジェクトの特異クラスにモジュールをインクルードして特異メソッドを定義。

サンプル

# encoding: utf-8
require "pry"

class Hoge
  def hoge
    puts "hoge"
  end
end

hoge = Hoge.new

module Hageable
  def hage
    puts "hage"
  end
end

class << hoge
  include Hageable
end

puts hoge.singleton_methods

出力

hage