Feature image depicting code snippets for Ruby's Hash#except method as discussed in this week’s "TWIL" post on efficient coding.

Embark on a journey of micro-learning with "TWIL," our weekly series that enriches your grasp on software development one byte at a time. In this iteration, Katie unravels the simplicity of refining code with Ruby's Hash#except method – an elegant alternative to key-by-key hash manipulation that preserves the sanctity of your original data structure. Bid farewell to mutilating your hashes and embrace the harmony of non-destructive updates using Hash#except.

Hash#except

I recently encountered a case where I wanted to remove the first handful or so keys from a hash, leaving the remaining keys and values (both of arbitrary quantity and content, so not something that could be grabbed using Hash#slice, for example.

My previous approach involved deleteing the keys from the hash (grabbing the values if/when needed) and returning the remaining hash, something like:

x = { a: 1, b: 2, c: 3, d: 4 }
x.delete(:a) # => 1
x.delete(:b) # => 2
x            # => {:c=>3, :d=>4}

This requires multiple lines and method calls for a fairly simple task and, more importantly, modifies the original hash.

Enter Hash#except, which functions like slice and returns all keys/values except those specified, and does it as a new hash, so the original hash is untouched:

y = { a: 1, b: 2, c: 3, d: 4 }
y.except(:a, :b) # => {:c=>3, :d=>4}
y                # => {:a=>1, :b=>2, :c=>3, :d=>4}

Resources

  • Ruby
Katie Linero's profile picture
Katie Linero

Senior Software Engineer

Related Posts

Illustration of a small, determined knight in weathered medieval armor and a bucket helmet, wearing a tattered red cape, striding across barren cracked earth with sword drawn, surrounded by a swirling cloud of scattered wooden alphabet letters representing Token Guard, a GitHub Action that monitors and guards against token context bloat in AI coding agent workflows by counting the tokens in LLM instruction files committed to repositories."
February 10, 2026 • Frank Valcarcel

Token Guard: Keeping Your Agent Context Lean in CI

Token Guard is a GitHub Action that counts tokens in your agent context files and enforces limits in CI. Here’s why we check agent context into our repos, and why keeping it lean matters for team collaboration.

Software engineer reviewing code during a code audit, analyzing source code on a monitor alongside documentation in a modern office environment.
February 18, 2025 • Frank Valcarcel

How We Review and Audit Software

A thorough code audit goes beyond automated scanners. Here is how we evaluate security, architecture, maintainability, compliance, and what you can expect when you work with us.

Let's work together

Tell us about your project and how Cuttlesoft can help. Schedule a consultation with one of our experts today.

Contact Us