Help us understand the problem. What is going on with this article?

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

前置き

これまで、複数の 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} 毎回答えは変わります。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした