ruby · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put things in order and gather them into groups.
.sort puts numbers smallest first and strings in alphabetical order. lets the block pick what to sort on, like each film's length. .reverse flips the order, .first(3) keeps the first three items, and .max_by finds the item with the biggest answer.
builds a hash. The block's answer for each item becomes a key, and every item with that answer lands in the same array.
You can methods: each one works on the result of the one before, reading left to right.
films = [
{ title: "Up", mins: 96 },
{ title: "Cars", mins: 117 },
{ title: "Coco", mins: 105 }
]
p films.sort_by { |film| film[:mins] }.map { |film| film[:title] }
p films.max_by { |film| film[:mins] }[:title]
p [5, 12, 8, 3].group_by { |n| n.even? } Read a chain like a recipe: first sort, then pick out the titles.
guess first
Group the farm animals. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
animals = ["cat", "cow", "dog", "duck"]
p animals.group_by { |animal| animal.length }
your turn
Your turn. Make a top three.
Fill in a score for each player, then press run. The chain sorts them by score, flips the order and keeps the top three.
fix it
The podium has the wrong runners. Fix the chain!
- A chain runs left to right. Which happens first here: keeping three, or sorting?
- It keeps the first three times before sorting, so the fastest runner, at the end, never gets a look in.
- Swap the two methods round to times.sort.first(3), then press run.
nailed it
you can put anything in order now. :D
.sort_bysorts on whatever the block works out..group_bybuilds a hash of arrays from the block's answers.- A chain runs left to right, one method after another.
new words in your collection
- sort_by
- group_by
- chain
This lesson isn’t saved. A free account remembers every lesson you finish.