CodeBiker
CodeBiker

Reputation: 3253

Extracting date values from hashes within Ruby array

I have an array that contains a series of hashes as listed below.

[{:pgs=>6, :oo=>"No", :ms_no=>"D3273", :auth=>"Johnson", :ms_recd=>"Mar 14", :ready_for_ce=>"Mar 15", :proj_back_from_ce=>"Apr 1", :final_ok=>"Jul 25", :pub_date=>"Aug 5", :notes=>" "}, 
{:pgs=>17, :oo=>"No", :ms_no=>"R4382", :auth=>"Jacobs", :ms_recd=>"Apr 12", :ready_for_ce=>"Apr 16", :proj_back_from_ce=>"May 17", :final_ok=>"Jul 10", :pub_date=>"June 10 ", :notes=>" "},
{:pgs=>15, :oo=>"No",  :ms_no=>"L3291", :auth=>"Smith", :ms_recd=>"Mar 25", :ready_for_ce=>"Mar 26", :proj_back_from_ce=>"Apr 22", :final_ok=>"Jun 21", :pub_date=>"Aug 10 ", :notes=>"Au prompted for cx 4/30", nil=>" 5/15."}]

I need to take two take two date values within each hash: the one with the key :ms_recd and the one with the key :pub_date. I then will determine how many days spanned between the two date ranges (for example, 18 days).

Fortunately, I have the last part pretty much figured out. I just need to do

ms_recd1 = DateTime.parse('Apr 24')
pub_date1 = DateTime.parse('Aug 15')
(pub_date1 - ms_recd1).to_i 

Which returns 115 (meaning 115 days). So let's say for three hashes, I'll pull out date ranges of 115, 162, and 94 days, and then I'd average it to 123.6 days.

My question is, how do I pull these date values out of this array to do this? I feel like this should be simple, but I can't figure out how it should work.

Upvotes: 0

Views: 167

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

My question is, how do I pull these date values out of this array to do this?

You could write as to get those dates :

 array.map{|h| h.values_at(:ms_recd,:pub_date)}

Full solution as @robertodecurnex commented :

 array.map{|h| (DateTime.parse(h[:pub_date]) - DateTime.parse(h[:ms_recd])).to_i}

Upvotes: 2

Related Questions