Skip to Main Content
TWIL
Ruby
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

Digital pioneer journeying through technological quirks, reminiscent of vast waterfalls and rocky terrains
April 5, 2017 • Kyle Misencik

Infinitely dispatching actions + React, Redux & React Router v4

While implementing JWT for an application, we ran into a quirk with React Router v4. Here, we hope to show how to implement protected client-side routes while avoiding some of the pitfalls we encountered.

Featured image for TWIL blog post on React Debugging and UI enhancement with React Suspense.
June 16, 2022 • Frank Valcarcel

TWIL 2022-06-10

Discover new insights in software development with TWIL: This week, learn streamlined React debugging techniques and how to enhance UIs using React Suspense.