DEV Community

Cover image for Lazy Method: Just the Basics
Kelly
Kelly

Posted on • Updated on

Lazy Method: Just the Basics

Recently I've been working with Ruby as I upskill. During this I have come across some enumerable methods such as, lazy and zip, that I think are interesting and likely highly useful in certain circumstances, but not as common as, the ones used for sorting, collecting, and selecting. In this post we'll be talking about lazy.

What do we mean by lazy in Ruby and why would we want to use it?
Lazy is a special type of enumerator, that allows for the construction of chains of operations and evaluating them on an as-needed basis. Lazy was added to Ruby as a way to improve performance by reducing unnecessary memory consumption when dealing with huge amounts of data. Since it is designed to be chained with other enumerable methods it actually overrides some of them so that the array is only iterated over once with a lazy analogue.

Let's look at an example:

Assume that we have 1000 user profiles from a pet lovers forum. Let's say, we would like to get 10 user profiles in which the user has a pet bird.

Image description

Image description

In the above example the first approach does not use the lazy enumerator so in order to return the sample of 10 users we want the whole array is iterated even if the first 10 users just happen to have pet birds. In the second example with the lazy enumerator each user is fetched one-by-one without iterating over all 1000 users at once. The loop ends when 10 users are fetched who meet the required condition, having a bird.

An important thing to note with the #lazy method is that it is not actually faster with smaller arrays according to post-release testing but it is is still useful for when the evaluation of the whole chain is too expensive or not possible.

Finally, the lazy method must be called with a code block, even if it is chained to a method that does not require one.

Calling .map on an array

Calling .lazy.map without a block causes an error

Use this method a bunch? Experimenting with unfamiliar techniques? Either way I'd love to hear how you like to use .lazy best. Good luck with breaking stuff, figuring it out, and savoring the satisfaction of the "Ah Ha!" momement. Happy Coding!

references:
Ghorpade, A. (2019, Oct 23,). Ruby lazy enumerators. Retrieved from https://blog.saeloun.com/2019/10/23/ruby-lazy-enumerators.html

Mihailov, I. (2012, -03-13T11:24:09+00:00). Ruby 2.0 enumerable::Lazy. Retrieved from https://railsware.com/blog/ruby-2-0-enumerablelazy/

Top comments (0)