Skip to content

Commit

Permalink
Add section about Enumerable#lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
ydakuka committed Dec 17, 2023
1 parent 5b7e0c2 commit e86c786
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4954,6 +4954,31 @@ LOREM
"when an unknown printer took a galley of type and scrambled it to make a type specimen book."
----

== Enumerable

=== Leverage `#lazy` to Optimize Memory Usage [[leverage-lazy-to-optimize-memory-usage]]

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.

Enumerator::Lazy can be constructed from any Enumerable with the `Enumerable#lazy` method without evaluating them immediately, and evaluating values on as-needed basis.

The real enumeration is performed when any non-redefined Enumerable method is called.

[source,ruby]
----
# bad
(0..).uniq { |x| x + 2 }.first(10)
(0..10000000).select { |x| x + 2 }.take(10)
# good
(0..).lazy.uniq { |x| x + 2 }.first(10)
(0..10000000).lazy.select { |x| x + 2 }.take(10)
----

=== Convert Lazy Enumerator to a Normal Enumerator with `#eager` [[convert-lazy-enumerator-to-a-normal-enumerator-with-eager]]

`Enumerable#eager` converts a lazy enumerator back to a non-lazy Normal Enumerator for compatibility with methods that expect standard enumerable object.

== Heredocs

=== Squiggly Heredocs [[squiggly-heredocs]]
Expand Down

0 comments on commit e86c786

Please sign in to comment.