Reputation: 2130
I need to get a new Ruby hash based on an existing hash but with one element removed and without affecting the original hash. I'm sure it's really simple, and I'm too much of a Ruby newbie to spot it.
For example, if I have plugh={:bar=>"bar", :baz=>"baz"}
I want to be able to do something like xyzzy=plugh.some_magic_goes_here(:baz)
and get xyzzy
set to {:bar=>"bar"}
without affecting plugh
in any way. How do I do it?
Upvotes: 0
Views: 115
Reputation: 37409
If you are not using active support, you can do the following:
xyzzy = plugh.reject { |k, _| k == :baz }
Upvotes: 6
Reputation: 8402
If you're using Rails (or at least ActiveSupport), then except is what you want:
xyzzy = plugh.except(:baz)
If you're not using Rails, the docs include the source code as well:
def except(*keys)
dup.except!(*keys)
end
def except!(*keys)
keys.each { |key| delete(key) }
self
end
Upvotes: 2