Created
September 27, 2017 10:58
-
-
Save Peranikov/8a1f2f526ff2a47ce29f713f4c697323 to your computer and use it in GitHub Desktop.
5-5-4 Enumerator::Lazy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby2.0からEnumerator::Lazyが追加された | |
(0..Float::INFINITY).map { |n| n.succ }.select {|n| n.odd?}.take(3) # 返ってこない | |
# lazyによって必要な分だけ計算し結果を得ることができる | |
odd_numbers = (0..Float::INFINITY).lazy.map { |n| n.succ }.select {|n| n.odd?}.take(3) | |
odd_numbers.force # => [1, 3, 5] | |
# lazyを用いた場合は要素を繰り返す度にmapとselectが実行されていることがわかる | |
(0..Float::INFINITY).lazy.map { |n| | |
puts "map: #{n}" | |
n.succ | |
}.select { |n| | |
puts "select: #{n}" | |
n.odd?}.take(3).force | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment