×

ruby · level 3 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.