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
tallycounts occurrences into a hash in one call.each_slicechunks a list;each_conswalks overlapping windows.chunk_whilegroups neighbors that satisfy the block.
Keywords and builtins used here
puts
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.
Step 2 of 3 in Enumerable, step 14 of 29 in Language basics.