๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Grouping

The last lessons rebuilt lists and folded them into one value. This lesson sorts a list into labelled groups.

Group words by length

group_by runs the block on each word. Words with the same block result land in the same group.

words = ["cat", "horse", "dog", "cow", "elephant"]
groups = words.group_by { |w| w.length }
p groups

Group numbers by a true or false key

The block can give a true or false result. The hash then holds one group for each of the two results.

numbers = [1, 2, 3, 4, 5, 6]
groups = numbers.group_by { |n| n.even? }
p groups

Partition splits a list in two

partition makes one pass and returns two arrays. The matches form the first array and the rest form the second array.

numbers = [12, 5, 20, 7, 30]
big, small = numbers.partition { |n| n >= 10 }
p big
p small

Tally counts the repeats

tally counts each different item in a list. The result is a hash of items and their counts.

votes = ["red", "blue", "red", "green", "blue", "red"]
counts = votes.tally
p counts

Example

names = ["Ana", "Al", "Ben", "Bo", "Cid"]
groups = names.group_by { |name| name.length }
p groups
puts groups[2]

Key points

  • group_by sorts items into a hash.
  • The block result becomes the key for each item.
  • Each key holds an array of its items.
  • partition splits a list into two arrays.
  • The first array holds the matches and the second holds the rest.
  • tally counts how many times each item appears.

In this example, group_by sorts the names by their length. The three-letter names form one group and the two-letter names form the other group. The last statement prints the two-letter group, one name per line.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does ["a", "b", "a"].tally return?