Class: Array

Inherits:
Object show all
Defined in:
lib/kaki/utils/nest_loop.rb

Instance Method Summary collapse

Instance Method Details

#nest_loopArray

任意の階層だけ繰り返しを行い、ブロックの返り値を順に配列に入れて返す。ブロックが与えられていなければ Enumerator を返す。

Returns:



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/kaki/utils/nest_loop.rb', line 4

def nest_loop
  check = lambda do |obj|
    return 0...obj if obj.class.ancestors.include?(Integer)
    obj
  end
  
  e = Enumerator.new do |y|
    ns = lambda do |ax, args|
      a, ax = ax.first, ax.drop(1)
      for i in check.call(a)
        nxt = args + [i]
        if ax.empty?
          y << nxt
        else
          ns.call(ax, nxt)
        end
      end
    end
    ns.call(self, [])
  end
  block_given? ? e.each.with_object([]) {|i, h| h << yield(i)} : e
end