From cd1789d56d381a0494e9deec9ba56e35f5484361 Mon Sep 17 00:00:00 2001 From: Yauheni Dakuka Date: Fri, 15 Dec 2023 16:58:39 +0400 Subject: [PATCH] Add section about Enumerable#lazy --- README.adoc | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.adoc b/README.adoc index 139b7db7..8e1278db 100644 --- a/README.adoc +++ b/README.adoc @@ -4950,6 +4950,28 @@ LOREM "when an unknown printer took a galley of type and scrambled it to make a type specimen book." ---- +== Enumerable + +=== lazy [[lazy]] + +Use `Enumerable#lazy` in combination with methods like `.first` or `.take`, especially for operations on large collections or datasets, because it avoids the need to process the entire collection. + +[source,ruby] +---- +SIZE = 10 +MAX = 10_000_000 + +# bad +(0..MAX).uniq { |x| x + 2 }.first(SIZE) +(0..MAX).map { |x| x + 2 }.first(SIZE) +(0..MAX).select { |x| x + 2 }.take(SIZE) + +# good +(0..MAX).lazy.uniq { |x| x + 2 }.first(SIZE) +(0..MAX).lazy.map { |x| x + 2 }.first(SIZE) +(0..MAX).lazy.select { |x| x + 2 }.take(SIZE) +---- + == Heredocs === Squiggly Heredocs [[squiggly-heredocs]]