kemra102
kemra102

Reputation: 531

Deleting NilClass values from hashes

I want to remove values of NilClass from a hash:

args = { 'name' => 'myname', 'description' => NilClass, 'homepage' => NilClass,
         'private' => NilClass, 'has_issues' => NilClass, 'has_wiki' => false,
         'has_downloads' => NilClass }

I tried the following:

args.reject!{|k,v| v.nil?}

This returns the original hash with all values still present.

Upvotes: 0

Views: 88

Answers (2)

Wender Freese
Wender Freese

Reputation: 117

You can make a monkeypatching and add a compact method to your hash class as described on this post.

Removing all empty elements from a hash / YAML?

Upvotes: 0

Richard Hamilton
Richard Hamilton

Reputation: 26444

You had the right idea, however the value of NilClass in Ruby is not nil. Try it out yourself?

NilClass.nil?
=> false

You have to specifically reject values equal to NilClass.

args.reject! { |key, value| value == NilClass }

Upvotes: 5

Related Questions