How would I go about deleting an array of keys in a hash? For example, you can call:
hash.delete(some_key)
But how can I do this:
hash.delete([key1,key2,key3,...])
without needing to looping manually.
How would I go about deleting an array of keys in a hash? For example, you can call:
hash.delete(some_key)
But how can I do this:
hash.delete([key1,key2,key3,...])
without needing to looping manually.
You can iterate over an array of keys and delete everyone of them:
[key1, key2, key3].each { |k| some_hash.delete k }
Can't remember any better solution.
This is exactly what you are looking for... You can do it like this without looping through the array unnecessarily.
keys_to_delete = [key1, key2, key3]
hash_array.except!(*keys_to_delete)
The result is stored in hash_array
You can try to use Hash#delete_if:
delete_if deletes every key-value pair from hsh for which block evaluates to true.
array_hash.delete_if { |key, _| [key1, key2, key3].include? key }
UPDATE
If you don't want to iterate over array of keys, you can use Set instead of Array (since Set uses Hash as storage include? is O(1)):
require 'set'
keys = [key1,key2,key3].to_set
array_hash.delete_if { |key, _| keys.include? key }
Maybe it's worth to make a method
class Hash
def delete_by_keys *keys
keys.each{|k| delete(k)}
end
end
hash_array.delete_by_keys(key1,key2,..)
keys.map instead of keys.each returns deleted values array. useful.ActiveSupport (part of Rails) implements exactly this, as Hash#except and Hash#except!
def except!(*keys)
keys.each { |key| delete(key) }
self
end