How do I remove a nil key from my hash?

Viewed 1477

With Ruby 2.4, I want to count the number of occurrences of an element and store them in a hash. However, I don't want to include any nil keys in my hash. So I tried

my_hash = int_data_col.each_with_object(Hash.new(0)) { |i, h| h[i]+=1 }.delete(nil)

but this returns "1". If I leave off the "delete(nil)", it returns a hash, but then a nil key is included in the hash (assuming a nil was present in the "int_data_col" array). How do I remove the nil key from my hash and still get the correct results?

3 Answers
Related