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

Frank Valcarcel speaking at Denver Startup Week 2018 on healthcare technology and HIPAA compliance, highlighting the digital revolution in healthcare IT
October 5, 2018 • Frank Valcarcel

Scaling Healthcare Technologies at DSW 2018

Discover the transformative journey of healthcare technology at Denver Startup Week 2018 with Frank . Dive into the world of healthcare software, product management, and the critical balance between innovation and HIPAA compliance.

August 18, 2024 • Frank Valcarcel

What makes Enterprise Software Development Different?

Enterprise software powers large organizations, handling complex tasks across departments. From robust security to scalability, these solutions face unique challenges. Explore what makes software “enterprise-ready” and how to choose the right development approach for your business.