Last active
March 30, 2017 22:29
-
-
Save chsh/0ffe801e2243059fb9f4a6d01770eaa6 to your computer and use it in GitHub Desktop.
Dimensional repeat executor.
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
# | |
# usage: [2,2,2].times { |i,j,k| do something... } | |
# | |
class Array | |
def times(&block) | |
raise unless block_given? | |
return nil if empty? | |
dim_call__(nil, self, &block) | |
end | |
private | |
def dim_call__(stack, dims, &block) | |
stack ||= [] | |
if dims.size == 0 | |
block.call(*stack) | |
else | |
t = dims[0] | |
l = dims[1..-1] | |
t.times do |i| | |
stack.push(i) | |
dim_call__(stack, l, &block) | |
stack.pop | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment