Non destructive way of deleting a key from a hash

hash, ruby, side-effects

Solution

ActiveSupport provides a hash extension: Hash#except. It allows you to return a new hash except specified keys without modifying the original.

Assuming you have installed the active_support gem:

ruby-1.9.3> require 'active_support/core_ext/hash/except.rb'
 => true
 ruby-1.9.3> a = {x: 2, y: 1, z: 3}
 => {:x=>2, :y=>1, :z=>3} 
ruby-1.9.3> b = a.except(:x)
 => {:y=>1, :z=>3} 
ruby-1.9.3> c = a.except(:x, :y)
 => {:z=>3} 
ruby-1.9.3> a
 => {:x=>2, :y=>1, :z=>3} 
ruby-1.9.3> b
 => {:y=>1, :z=>3} 
ruby-1.9.3> c
 => {:z=>3} 

Problem

Is there a non-destructive way of deleting a key value pair from a hash? For example, if you did ``` original_hash = {:foo => :bar} new_hash = original_hash new_hash = new_hash.reject{|key, _| key == :foo} ``` or ``` original_hash = {:foo => :bar} new_hash = original_hash new_hash = new_hash.dup new_hash.delete(:foo) ``` then `original_hash` is unchanged, and `new_hash` is changed, but they're a tad verbose. However, if you did ``` original_hash = {:foo => :bar} new_hash = original_hash new_hash.delete(:foo) ``` then `original_hash` is changed, which isn't what I want. Is there a single method that does what I want?

Original source