Last active
August 29, 2015 14:20
-
-
Save hassox/1aefc9a26bca23f6ae8a to your computer and use it in GitHub Desktop.
This file contains 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
$ ruby stacked_blocks.rb | |
START ARRAY THINGS | |
START ONE | |
START TWO | |
START THREE | |
START FOUR | |
IN THE MIDDLE OF ARRAYS DOING IT | |
FINISH FOUR | |
FINISH THREE | |
FINISH TWO | |
FINISH ONE | |
FINISH ARRAY THINGS |
This file contains 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
class Array | |
# Stacks method calls that take blocks | |
# so that each method call is nested in the block of the previous one | |
def stack_block_calls(callee, &blk) | |
empty? ? yield : first.send(callee) { self[1..-1].stack_block_calls(callee, &blk) } | |
end | |
end | |
$indent = 0; | |
MSG = ->(msg) { | |
ident = " " * $indent | |
puts "#{ident}#{msg}" | |
} | |
class BlockThing | |
attr_accessor :name | |
def initialize(name) | |
@name = name | |
end | |
def do_it | |
$indent += 2 | |
MSG["START #{name}"] | |
yield | |
ensure | |
MSG["FINISH #{name}"] | |
$indent -= 2 | |
end | |
end | |
arry = [ | |
BlockThing.new("ONE"), | |
BlockThing.new("TWO"), | |
BlockThing.new("THREE"), | |
BlockThing.new("FOUR"), | |
] | |
MSG["START ARRAY THINGS"] | |
arry.stack_block_calls(:do_it) { | |
$indent += 2 | |
MSG["IN THE MIDDLE OF ARRAYS DOING IT"] | |
$indent -= 2 | |
} | |
MSG["FINISH ARRAY THINGS"] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment