Skip to content

Instantly share code, notes, and snippets.

@chsh
Last active March 30, 2017 22:29
Show Gist options
  • Save chsh/0ffe801e2243059fb9f4a6d01770eaa6 to your computer and use it in GitHub Desktop.
Save chsh/0ffe801e2243059fb9f4a6d01770eaa6 to your computer and use it in GitHub Desktop.
Dimensional repeat executor.
#
# 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