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

ブロックを取るRubyのProcはEnumerator化することができるか

Last updated at Posted at 2025-04-09

結論。できる。
 
ブロックを取るメソッドの Enumerator化は、enum_forto_enumでできる。

def foo
  (1..10).each { yield(_1) }
end

enum_for(:foo).map { _1 * 2 }
#=>[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

では、ブロックを取る Procオブジェクトは、Enumerator::Yielder#to_procを使って Enumerator化できるのである。

foo = ->(&bk){
  (1..10).each { bk.call(_1) }
}

Enumerator.new { |y| foo.(&y) }.map { _1 * 2 }
#=>[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

※参考
https://qiita.com/obelisk68/items/8518159d1eba55397a9a
https://docs.ruby-lang.org/ja/latest/method/Enumerator=3a=3aYielder/i/to_proc.html

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