Created
June 16, 2012 18:38
-
-
Save rjungemann/2942209 to your computer and use it in GitHub Desktop.
Defines `reverse_evaluate`, which takes a block and evaluates its contents in reverse order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Defines a macro in Ruby which takes a block, and evaluates the | |
# block's statements in reverse order. | |
# | |
# Requires the 'live_ast' and 'ruby2ruby' gems. Install via: | |
# | |
# gem install live_ast ruby2ruby | |
# | |
# Should work in 1.8 as well as 1.9. | |
require 'rubygems' | |
require 'live_ast' | |
require 'ruby2ruby' | |
def forward_evaluate(&block) | |
block.call | |
end | |
def reverse_evaluate(&block) | |
r2r = Ruby2Ruby.new | |
ast = block.to_ast | |
pp ast | |
ast2 = Sexp.new \ | |
ast[0], | |
Sexp.new(:call, nil, :forward_evaluate, Sexp.new(:arglist)), | |
ast[2], | |
( [ ast[3][0] ] + ast[3][1..-1].reverse ) | |
eval r2r.process(ast2) | |
end | |
################################################################ | |
def first | |
puts 'first' | |
end | |
def second | |
puts 'second' | |
end | |
def third | |
puts 'third' | |
end | |
# evaluate statements in a block in normal order | |
f = lambda { | |
first | |
second | |
third | |
} | |
f.call | |
# first | |
# second | |
# third | |
# evaluate statements in a block in reverse order | |
reverse_evaluate do | |
first | |
second | |
third | |
end | |
# third | |
# second | |
# first |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment