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

Read a file into a string in Go Systems os.ReadFile replaced ioutil.ReadFile in 1.16 and is the one-liner for small files. Walk a directory tree lazily Python pathlib keeps the paths as objects rather than strings, so joining and suffix checks stay readable. Prepared statement with PDO PHP Placeholders rather than interpolation. This is the whole of SQL injection defence in PHP. Undo the last commit but keep the changes Git Moves HEAD back one commit and leaves everything staged, which is what you usually want after committing too early. Check a malloc result in C Systems The allocation that nobody checks is the one that fails in production. Find the commit that introduced a bug Git Binary search across history. Mark a known good and a known bad commit and git narrows it down for you. Nullable reference types in C# Systems Turning the feature on makes the compiler point at every place a null could slip through. A dataclass with validation Python __post_init__ runs after the generated constructor, which is where cheap invariants belong.
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 6
  • 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