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