×

ruby · level 2 · unit 2 · lesson 4

  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

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.