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.
Ruby | Array delete() operation Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.
Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With