0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

to_enum

Last updated at Posted at 2024-12-27

Enumeratorクラスに変換する

to_enum(method = :each, *args) -> Enumerator[permalink][rdoc][edit]
enum_for(method = :each, *args) -> Enumerator
to_enum(method = :each, *args) {|*args| ... } -> Enumerator
enum_for(method = :each, *args) {|*args| ... } -> Enumerator

Enumerator.new(self, method, *args)を返します。

ブロックを指定した場合は Enumerator#size がブロックの評価結果を返します。ブロックパラメータは引数 args です。

[PARAM] method:
メソッド名の文字列かシンボルです。
[PARAM] args:
呼び出すメソッドに渡される引数です。

str.enum_forでEnumeratorクラスが生成されメソッド(each_byte)が繰り返し実行されている

irb(main):008> str = "xyz"
irb(main):009>
irb(main):010> enum = str.enum_for(:each_byte)
irb(main):011> p(a = enum.map{|b| '%02x' % b }) #=> ["78", "79", "7a"]
irb(main):012>
irb(main):013> # protects an array from being modified
irb(main):014> a = [1, 2, 3]
irb(main):015> p(a.to_enum)
["78", "79", "7a"]
#<Enumerator: [1, 2, 3]:each>
=> #<Enumerator: ...>

Enumeratorクラス ブロック処理するときに使うクラス 使用するにはeachメソッドが必要

each 以外のメソッドにも Enumerable の機能を提供するためのラッパークラスです。また、外部イテレータとしても使えます。

Enumerable モジュールは、Module#include 先のクラスが持つ each メソッドを元に様々なメソッドを提供します。例えば Array#map は Array#each の繰り返しを元にして定義されます。 Enumerator を介することにより String#each_byte のような異なる名前のイテレータについても each と同様に Enumerable の機能を利用できます。

Enumerator を生成するには Enumerator.newあるいは Object#to_enum, Object#enum_for を利用します。また、一部のイテレータはブロックを渡さずに呼び出すと繰り返しを実行する代わりに enumerator を生成して返します。

Enumeratorを介することでeach と同様に Enumerable の機能を利用できる

イテレータとは

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?