Code Snippets Sign in

Group and count in Ruby

Ruby

tally does the counting; group_by keeps the members when you need them.

words.tally
#=> {"the"=>12, "and"=>7}

orders.group_by(&:status)
      .transform_values(&:count)
Download
Ruby ruby enumerable chris

More in Ruby

Safe navigation and fetch in Ruby Ruby &. stops at nil; fetch raises rather than returning nil when a key is genuinely required.

Random picks

Iterate and collect in Rust Systems Filter and map fuse into a single pass; collect decides what comes out the other end. Responsive grid without media queries Web & CSS auto-fill with minmax reflows on its own, so the column count follows the container rather than a breakpoint list. Time a block of code Python A context manager that prints how long its body took, without scattering time.perf_counter calls through the function. Serve the current directory over HTTP Shell Three ways to put a folder on localhost when you need to test something quickly. Freeze time in a test Testing Node's mock timers make anything date-dependent deterministic without injecting a clock everywhere. Find the largest files under a directory Shell Sorts everything beneath the working directory by real disk usage and shows the twenty worst offenders. Merge dictionaries Python The | operator returns a new dict; |= updates in place. Later keys win in both. Truncate text to a number of lines Web & CSS Ellipsis after two lines. The -webkit- prefixes are still required despite being supported everywhere.
Recently added
  • Find the largest files under a directory
  • Delete files older than thirty days
  • Watch a command until it succeeds
  • Show which process is holding a port
  • Rename a batch of files with a pattern
  • Tail a log and colour only what matters
  • Make a shell script fail loudly
  • Count lines of code by extension
  • Run a command on every file changed in a commit
  • Serve the current directory over HTTP
Categories
  • Build & CI 4
  • Containers 5
  • Data Formats 4
  • Databases 8
  • Git 8
  • JavaScript 10
  • Networking 6
  • PHP 3
  • Python 8
  • Ruby 2
  • Security 6
  • Shell 11
  • Systems 11
  • Testing 4
  • Text Processing 7
  • TypeScript 5
  • Web & CSS 7
  • wordpress 1
© 2026 Code Snippets