Letokteren
Letokteren

Reputation: 809

Delete element from nested hash in Ruby

I have a two dimensional hashes in Ruby.

h = { "a" => {"v1" => 0, "v2" => 1}, "c" => {"v1" => 2, "v2" => 3} }

I would like to delete those elements from the hash, where value 1 (v1) is 0, for example, so my result would be:

{ "c" => {"v1" => 2, "v2" => 3} }

I wanted to achieve this by iterating trough the hash with delete_if, but I'm not sure how to handle the nested parts with it.

Upvotes: 0

Views: 1005

Answers (2)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

Is that what you're looking for?

h.delete_if { |_, v| v['v1'].zero? }
#=> {"c" => {"v1" => 2, "v2" => 3}}

As @TomLord says, it also may be variant, when v1 can be not defined or equal to nil, in this case, it would be better to use v['v1'] == 0

Upvotes: 3

Sagar Pandya
Sagar Pandya

Reputation: 9497

You can use Hash#value? in your block to check if any of the values in the nested hashes equal 0:

hash.delete_if { |k,v| v.value? 0 } #=> { "c" => { "v1" => 2, "v2" => 3 } } 

Upvotes: 1

Related Questions