3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyのtimesメソッドを多次元に拡張してみる

Last updated at Posted at 2017-03-30

rubyには 3.times { |i| do something } みたいな便利なメソッドがあるが、これを二次元以上でもできたら便利かなと思ったので書いてみた。

すでにありそうな気もするし、クラスにダイレクトにメソッドを突っ込むのもどうかと思うのだが、実装例ということでとりあえず。 ;-)

[2,2].times { |i,j| puts "#{i},#{j}" }

というような感じで使います。

#
# 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

gist:
https://gist.github.com/chsh/0ffe801e2243059fb9f4a6d01770eaa6

3
6
14

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?