Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete array of keys in Ruby Hash

Tags:

arrays

ruby

hash

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.

like image 659
Artem Kalinchuk Avatar asked Feb 01 '12 13:02

Artem Kalinchuk


People also ask

How do you destroy an Array in Ruby?

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.

What is Array of hashes in Ruby?

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.

What is Hash function in Ruby?

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.


2 Answers

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.

like image 123
KL-7 Avatar answered Sep 18 '22 00:09

KL-7


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

like image 36
thegauraw Avatar answered Sep 20 '22 00:09

thegauraw