-2

I have two hash max and min contain same key

max

{22479=>2018-05-24 20:15:11 UTC, 15392=>2018-04-24 09:38:32 UTC, 16319=>2018-04-27 02:21:53 UTC, 24644=>2018-06-07 20:01:04 UTC, 21551=>2018-05-19 20:11:11 UTC, 17876=>2018-05-03 15:47:54 UTC, 22467=>2018-05-24 17:11:15 UTC}

min

{22479=>2018-05-24 20:15:03 UTC, 15392=>2018-04-24 09:38:15 UTC, 16319=>2018-04-27 02:21:53 UTC, 24644=>2018-06-07 19:59:23 UTC, 21551=>2018-05-19 20:11:04 UTC, 17876=>2018-05-03 15:47:54 UTC, 22467=>2018-05-24 17:11:15 UTC}

I want to create the third hash with difference of those two hashes in terms of time. Like,

diff

{22479=> 9, 15392=> 17,.......}

Can anybody help me out for this, what is the efficient way of dong this. Is have to iterate the loop two times.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
compsy
  • 233
  • 4
  • 12

1 Answers1

1

Input

max
 => {22479=>2018-05-24 20:15:11 UTC,
     15392=>2018-04-24 09:38:32 UTC,
     16319=>2018-04-27 02:21:53 UTC,
     24644=>2018-06-07 20:01:04 UTC,
     21551=>2018-05-19 20:11:11 UTC,
     17876=>2018-05-03 15:47:54 UTC,
     22467=>2018-05-24 17:11:15 UTC}

min
 => {22479=>2018-05-24 20:15:03 UTC,
     15392=>2018-04-24 09:38:15 UTC,
     16319=>2018-04-27 02:21:53 UTC,
     24644=>2018-06-07 19:59:23 UTC,
     21551=>2018-05-19 20:11:04 UTC,
     17876=>2018-05-03 15:47:54 UTC,
     22467=>2018-05-24 17:11:15 UTC}

Solution

Fetch common keys from max and min and calculate the difference in time (in seconds).

(max.keys & min.keys).each_with_object({}) do |k, out|
  out[k] = (max[k] - min[k]).to_i
end
 => {22479=>8,
     15392=>17,
     16319=>0,
     24644=>101,
     21551=>7,
     17876=>0,
     22467=>0} 
Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22
  • 2
    @DennyMueller: those are times, not strings – Sergio Tulentsev Jul 16 '18 at 11:46
  • yep my bad, was testing it like 10 seconds ago. I was initially assuming that op has json hashes and not time object and your solution looked like you just subtracted the strings and I was like "wow you can just subtract the string" – Denny Mueller Jul 16 '18 at 11:49