ruby · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
makes a chain do only the work it needs.
Normally map and select are : each one works through every item and builds a whole new array before the next step starts. On an endless range that never finishes, and on a million rows it wastes time. Add .lazy and the chain becomes lazy: each item travels through every step on its own.
Nothing happens until something asks for results. first(3) pulls items through one at a time and stops once it has three. to_a finishes a lazy chain too, but only when the chain has an end. Here a counter shows how few numbers the lazy chain touched.
checked = 0
squares = (1..).lazy.map do |n|
checked += 1
n * n
end
p squares.select(&:even?).first(3)
puts "Checked #{checked} numbers" Lazy chains cost a little extra per item, so use them for endless or very long data, not for five items.
guess first
How many prices get doubled? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
work = 0
doubled = [3, 8, 12, 5, 20, 7].lazy.map do |price|
work += 1
price * 2
end
puts doubled.find { |price| price > 10 }
puts work
your turn
Your turn. Find lucky numbers in an endless range.
Make the chain lazy in the first blank, then choose how many lucky numbers to take, from 1 to 10.
fix it
This prints a description, not the names. Fix it.
- The output describes a lazy chain instead of showing names. Has anything asked for the results?
- A lazy chain does no work until something like
firstorto_apulls items through. - Change the last line to
p shout.to_a, then press run.
nailed it
you made your chains lazy. :D
- Eager
mapandselectfinish every item before moving on. .lazysends items through the chain one at a time.firstorto_apulls results out of a lazy chain.
new words in your collection
- eager
- lazy
This lesson isn’t saved. A free account remembers every lesson you finish.