LoginSignup
3
2

More than 5 years have passed since last update.

RubyのEnumerableをstream風に処理する

Posted at

TL;DR

Enumerable#lazy (#force)を使えばよかった。

つらいと思っていたところ

RubyのEnumerable#mapみたいな処理はついついチェインして書きたくなってしまうんだけど、毎回オブジェクトが作成されていて非効率で辛いと思っていた。

p 5.times.map { |n|
  (n * 10).tap(&method(:puts))
}.select { |n|
  (n > 20).tap(&method(:puts))
}.map { |n|
  (n + 2).tap(&method(:puts))
}

=>
# 0
# 10
# 20
# 30
# 40
# false
# false
# false
# true
# true
# 32
# 42
# [32, 42]

そしたら

#lazyというのがあった。

-p 5.times.map { |n|
+p 5.times.lazy.map { |n|
   (n * 10).tap(&method(:puts))
 }.select { |n|
   (n > 20).tap(&method(:puts))
 }.map { |n|
   (n + 2).tap(&method(:puts))
-}
+}.force

いい感じに遅延実行してくれる。

p 5.times.lazy.map { |n|
  (n * 10).tap(&method(:puts))
}.select { |n|
  (n > 20).tap(&method(:puts))
}.map { |n|
  (n + 2).tap(&method(:puts))
}.force

=>
# 0
# false
# 10
# false
# 20
# false
# 30
# true
# 32
# 40
# true
# 42
# [32, 42]

バッチとか書くときにいいかも。
自分が情弱なだけだったけど知らない人もいそう。

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