LoginSignup
2
1

More than 3 years have passed since last update.

複数の Enumerable なオブジェクトで tally したい【結論】deep_each

Posted at

前置き

これまで、複数の Enumerable なオブジェクトで tally するためにあれこれ考え、

複数の Enumerable なオブジェクトで tally したい【追記あり】

を書き、@obelisk68 さんと色々やり取りをして、こんな示唆もいただきました。

Enumeratorを返すArray#flatten(Ruby)

現時点でのまとめ

それで、あれこれ考えてみたところ、結局、deep_each があればいいんじゃないか。

世の中にはいろんな実装例がありますが、簡単なのは、

module Enumerable
  def deep_each(&block)
    return to_enum(__method__) unless block_given?
    each do |e|
      case e
      when Enumerable
        e.deep_each(&block)
      else
        block.call(e)
      end
    end
  end
end

これがあれば、Array 以外のオブジェクトにも対応可能です。

enums = Enumerator.new(20) do |y|
  20.times do
    y << Enumerator.new(20) do |yy|
      20.times do
        yy << Enumerator.new(20) do |yyy|
          20.times do
            yyy << rand(1..5)
          end
        end
      end
    end
  end
end

enums.deep_each.tally
=> {4=>1579, 5=>1664, 2=>1564, 3=>1586, 1=>1607} 毎回答えは変わります。
2
1
0

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
2
1