Tbpgr Blog

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

メタプログラミングRuby | 魔術 | 遅延評価

概要

遅延評価

内容

Procやlambdaにコンテキストを保管して後から評価します。

サンプル

# encoding: utf-8
require "date"
require "pp"

class CodeStore

  def store(&block)
    @my_code_capsule ||= []
    @my_code_capsule << block
  end

  def execute
    @my_code_capsule.each do |p|
      puts p.call
    end
  end
end

code =<<EOS
  1+1
  "a".succ
  Date.today
EOS

code_store = CodeStore.new
code.each_line do |line|
  code_store.store do 
    eval(line)
  end
end
puts "only store. after execute"
code_store.execute
実行結果
only store. after execute
2
b
2013-08-16