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
sort_by(&:length)orders by whatever the block computes.min_byandmax_byfind extremes by the same rule.group_bybuckets elements into a hash keyed by the block.- An array key like
[-w.length, w]sorts by two criteria at once.
Keywords and builtins used here
puts
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.
Step 1 of 3 in Enumerable, step 13 of 29 in Language basics.