Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why and how to use lazy evaluation in Ruby? #9

Open
ccniuj opened this issue Oct 5, 2016 · 1 comment
Open

Why and how to use lazy evaluation in Ruby? #9

ccniuj opened this issue Oct 5, 2016 · 1 comment

Comments

@ccniuj
Copy link
Owner

ccniuj commented Oct 5, 2016

ref: Ruby 2.0 Enumerable::Lazy
ref: Ruby 2.0 Works Hard So You Can Be Lazy
ref: Functional Programming and Ruby by Pat Shaughnessy

What is lazy evaluation?

Lazy evaluation, or call-by-need, means the value of an variable is evaluated when it is needed, which is a opposite concept of call-by-name, or eager evaluation.

Why be lazy anyway?

For example, you want to map throw an array of integer to time 3 and plus 3:

arr = [1, 2, 3]
arr.map{ |i| i*3 }.map{ |i| i+3 }

Here is a problem: arr will be looped twice, since map is called one after one. As we can see, this expression actually generates 2 results whenever map is called. However, we only need the last result. How can we only get the last result without generating the intermediate result? Use lazy:

arr = [1, 2, 3]
arr.lazy.map{ |i| i*3 }.map{ |i| i+3 }.to_a

How to use ruby lazy?

Above example showcases one way to use lazy:

[1, 2, 3].lazy
# => #<Enumerator::Lazy: [1, 2, 3]>

And this lazy object can be chained by enumerable methods.

@Ricardo-Paul
Copy link

So good explanation. Thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants