D.Kamenov
D.Kamenov

Reputation: 83

Remove key from hash

I have to remove all keys which are representing empty string for example

inventory = {"4"=>"", "1"=>"51059441", "3"=>""}

And The result should be

inventory = {"1"=>"51059441"}

Upvotes: 0

Views: 3388

Answers (3)

peter
peter

Reputation: 42182

You were on the right track, but a hash needs two parameters, the key and the value

inventory.reject{ |key, value| value == ""}

gives

{"1"=>"51059441"}

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

Try reject:

=> {"4"=>"", "1"=>"51059441", "3"=>""}.reject { |_, y| y.empty? }
#> {"1"=>"51059441"}

The same as delete_if but works on a copy.

Upvotes: 1

Ilya
Ilya

Reputation: 13477

You can use Hash#delete_if:

hash.delete_if {|k, v| !v.present? }
#=> {"1"=>"51059441"}

Note: present? is a Rails method. You can use empty? instead if you want delete only empty strings and arrays.

Upvotes: 1

Related Questions