typestar

sort_by and group_by in Ruby

Ordering and bucketing with a key function instead of a comparator.

langs = %w[ruby python go rust c javascript]

puts langs.sort.inspect
puts langs.sort_by(&:length).inspect
puts langs.min_by(&:length)
puts langs.max_by(&:length)

by_initial = langs.group_by { |w| w[0] }
puts by_initial.inspect

# sort by two keys: length descending, then alphabetical
puts langs.sort_by { |w| [-w.length, w] }.inspect

How it works

  1. sort_by(&:length) orders by whatever the block computes.
  2. min_by and max_by find extremes by the same rule.
  3. group_by buckets elements into a hash keyed by the block.
  4. An array key like [-w.length, w] sorts by two criteria at once.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
336
Tokens
75
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 1 of 3 in Enumerable, step 13 of 29 in Language basics.

← Previous Next →