Skip to content

Commit e86c786

Browse files
committed
Add section about Enumerable#lazy
1 parent 5b7e0c2 commit e86c786

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.adoc

+25
Original file line numberDiff line numberDiff line change
@@ -4954,6 +4954,31 @@ LOREM
49544954
"when an unknown printer took a galley of type and scrambled it to make a type specimen book."
49554955
----
49564956

4957+
== Enumerable
4958+
4959+
=== Leverage `#lazy` to Optimize Memory Usage [[leverage-lazy-to-optimize-memory-usage]]
4960+
4961+
Using `Enumerable#lazy` in combination with methods like `Enumerable#first` or `Enumerable#take` can be very efficient, especially for operations on large collections, datasets and infinite sequences seamlessly.
4962+
4963+
Enumerator::Lazy can be constructed from any Enumerable with the `Enumerable#lazy` method without evaluating them immediately, and evaluating values on as-needed basis.
4964+
4965+
The real enumeration is performed when any non-redefined Enumerable method is called.
4966+
4967+
[source,ruby]
4968+
----
4969+
# bad
4970+
(0..).uniq { |x| x + 2 }.first(10)
4971+
(0..10000000).select { |x| x + 2 }.take(10)
4972+
4973+
# good
4974+
(0..).lazy.uniq { |x| x + 2 }.first(10)
4975+
(0..10000000).lazy.select { |x| x + 2 }.take(10)
4976+
----
4977+
4978+
=== Convert Lazy Enumerator to a Normal Enumerator with `#eager` [[convert-lazy-enumerator-to-a-normal-enumerator-with-eager]]
4979+
4980+
`Enumerable#eager` converts a lazy enumerator back to a non-lazy Normal Enumerator for compatibility with methods that expect standard enumerable object.
4981+
49574982
== Heredocs
49584983

49594984
=== Squiggly Heredocs [[squiggly-heredocs]]

0 commit comments

Comments
 (0)