:a, "20th Apr, 2013" => :b,"Tomorrow" => :c...">

How to extract only time elements from a hash?

I have a hash as shown below:

{"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e}

I need a conclusion:

as {"5:00 PM" => :d,"09:25 PM" => :e}

Can someone help me solve this problem?

+5
source share
3 answers
t = {"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e}

t.select { |k,v| Time.strptime(k,"%H:%M %P") rescue false }

#=>  {"5:00 PM"=>:d, "09:25 PM"=>:e}
+6
source
hash = {"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e}

hash.select { |k, v| k.match /\d{1,2}:\d{2} [AP]M/ }

Gives you:

{"5:00 PM"=>:d, "09:25 PM"=>:e}

As for the β€œperfect” regex, check out the re-war in other comments replies;)

0
source

More general approach:

 hash = {"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e , "23:23" => :f}

 hash.delete_if{|k,v| k !~ /\d{1,2}:\d\d/}
  => {"5:00 PM"=>:d, "09:25 PM"=>:e, "23:23" => :f} 

NOTE:

  • it also allows 24 hour time format
  • it also handles the case when the hour is only one digit

if you do not want to handle the 24-hour format, use:

 hash = {"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e , "23:23" => :f}

 hash.delete_if{|k,v| k !~ /\d{1,2}:\d\d/ [AaPp][Mm]} # am AM pm PM
  => {"5:00 PM"=>:d, "09:25 PM"=>:e} 
-2
source

All Articles