Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a nil key from my hash?

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?


2 Answers

Use Array#compact which removes all nil values before the count.

my_hash = int_data_col.compact.each_with_object(Hash.new(0)) { |i, h| h[i]+=1 }
like image 190
Sagar Pandya Avatar answered Dec 08 '25 02:12

Sagar Pandya


In Ruby 2.4, there's a way to do it which is very readable:

arr.compact.group_by(&:itself).transform_values(&:size)
like image 42
Mark Thomas Avatar answered Dec 08 '25 01:12

Mark Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!