Huw
Huw

Reputation: 645

Ruby: A neat way to find the number of non nil records from a Hashie::Mash

I'm using EJ Holme's rather excellent restforce gem to speak to my salesforce instance.

It's returning a hashie mash for a client record. I'd like to do a bit of built-in-method fu, but I'm getting stuck.

The hash returns around 550 array pairs of values. For instance Restforce_hash.last would return something like:

["field_title", "field_content">]

So far so great, I want to put a summary box at the top that displays a metric for how many fields are in use for the record.

If I call Restforce_hash.length I get the total number returned just fine.

However what I really want is the number of record pairs where the second item in the array (ie.. the "field_content" is not nil.

I was hoping there would be some great neat one-line ruby method for this like:

Restforce_hash.not_nil.length

But i'm not having just joy tracking something down... is there a way or do i have to iterate over the hash and count the number of != nil records?

Upvotes: 0

Views: 117

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

If you want to know how many nil values there are in a hash, just use:

hash = {a:1, b:nil, c:2}
hash.values.count{ |v| !v } # => 1

Upvotes: 0

Qaisar Nadeem
Qaisar Nadeem

Reputation: 2424

Restforce_hash.select{|key,value| value.present? }  

will return all the elements after excluding all the NIL + blank elements. if

     Restforce_hash={:a=> "sss", :b=>"cvcxc",:c=>"",:f=>nil}

then

    Restforce_hash.select{|key,value| value.present? } 

will return

{:a=>"sss", :b=>"cvcxc"}

Upvotes: 1

Uri Agassi
Uri Agassi

Reputation: 37409

Try this:

restforce_hash.count { |key, val| !val.nil? }

Upvotes: 2

Related Questions