ruby · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Power tools replace whole loops with one well-named method.
Beginners write a loop, an empty hash and a counter for every job. Professionals reach for a power tool whose name says what it does. counts how often each item appears. splits items into two arrays: the ones that pass a test and the ones that fail.
hands items out in groups of two, like seating guests at tables. loops while carrying one object, often a hash you fill in, and hands that object back at the end. They work on arrays, hashes and any class that includes Enumerable.
votes = ["tea", "coffee", "tea", "juice", "tea"]
p votes.tally
p [12, 45, 7, 60, 30].partition { |amount| amount >= 30 }
["Ana", "Ben", "Cy", "Di", "Ed"].each_slice(2) { |table| p table }
stock = ["apple", "pear"].each_with_object({}) { |fruit, counts| counts[fruit] = 0 }
p stock A well-named method tells the next reader what your code means before they read how it works.
guess first
Count the colours, then group them. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
colours = ["red", "blue", "red", "green", "red", "blue"]
p colours.tally
colours.each_slice(4) { |group| p group.length }
your turn
Your turn. Sort the week into warm days and the rest.
Put the power tool that splits items in two in the first blank, then choose how many degrees count as warm.
fix it
The sales totals crash. Fix the block.
- Read the error: Ruby was asked to mix a string and a number. Which variable holds what?
each_with_objecthands the block the item first and the carried hash second.- Swap the names between the bars on line 2 to
|sale, sums|, then press run.
nailed it
you swapped loops for power tools. :D
tallycounts how often each item appears.partitionsplits items into passes and fails.each_slicemakes groups, andeach_with_objectcarries a result along.
new words in your collection
- tally
- partition
- each_slice
- each_with_object
This lesson isn’t saved. A free account remembers every lesson you finish.