0

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Will the nested hashes always contain a 'v1' key, and will it always map to Numeric object? If not, it would be safer to use == 0 instead of .zero?.
1

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 } } 

2 Comments

the OP seems to only care about v1 in the sub hash so if v1 == 1 and v2 == 0 then this solution is inaccurate
@engineersmnky True, I've just added some explanation. I will leave the answer up as the OP may still find it useful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.