You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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:Here is a problem:
arr
will be looped twice, sincemap
is called one after one. As we can see, this expression actually generates 2 results whenevermap
is called. However, we only need the last result. How can we only get the last result without generating the intermediate result? Use lazy:How to use ruby
lazy
?Above example showcases one way to use
lazy
:And this lazy object can be chained by
enumerable
methods.The text was updated successfully, but these errors were encountered: