Skip to content

Instantly share code, notes, and snippets.

@hassox
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hassox/1aefc9a26bca23f6ae8a to your computer and use it in GitHub Desktop.
Save hassox/1aefc9a26bca23f6ae8a to your computer and use it in GitHub Desktop.
$ 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
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