typestar

tally and slices in Ruby

Counting and windowing built straight into Enumerable.

rolls = [4, 2, 6, 4, 4, 2, 1, 6]

puts rolls.tally.inspect
puts rolls.each_slice(3).to_a.inspect

# each_cons walks overlapping windows; count the upward moves
puts rolls.each_cons(2).count { |a, b| b > a }

letters = "mississippi".chars
puts letters.tally.max_by { |_, n| n }.inspect
puts letters.chunk_while { |a, b| a == b }.map(&:join).inspect

How it works

  1. tally counts occurrences into a hash in one call.
  2. each_slice chunks a list; each_cons walks overlapping windows.
  3. chunk_while groups neighbors that satisfy the block.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
347
Tokens
101
Three-star pace
70 tpm

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

Type this snippet

Step 2 of 3 in Enumerable, step 14 of 29 in Language basics.

← Previous Next →