Tbpgr Blog

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

Ruby | Module | module_exec/class_exec

概要

Module#module_exec(*args) {|*vars| ... } -> object[permalink][rdoc]
Module#class_exec(*args) {|*vars| ... } -> object

詳細

与えられたブロックを指定された args を引数としてモジュールのコンテキストで評価する。

サンプルコード
module Hogeable
  def hogeable
  end
end

class Hoge
  include Hogeable
  def hoge
    print 'hoge'
  end
end

CONST = 'const'
Hoge.module_exec(CONST) do |args|
  const_set(:HOGE_CONST, args)
  def hoge2
    puts Hoge::HOGE_CONST + 'hoge2'
  end
end

Hoge.new.hoge2

出力

出力

consthoge2