Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a hash from array of hashes in Ruby

Tags:

arrays

ruby

hash

I have an array of hashes as following:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]

Now, I want to first check whether the array contains a hash with key "k1" with value "v3". If yes, then I want to delete that hash from the array.

The result should be:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]
like image 314
user2823083 Avatar asked Oct 07 '13 06:10

user2823083


People also ask

How do you remove an item from a hash?

We can use the delete(key) method to delete an entry of a hash. It returns the associated value of the entry deleted.

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.


1 Answers

Use Array#delete_if:

arr = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]

arr.delete_if { |h| h["k1"] == "v3" }
#=> [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]

If there is no hash matching the condition, the array is left unchanged.

like image 158
Stefan Avatar answered Sep 27 '22 20:09

Stefan