Arup Rakshit
Arup Rakshit

Reputation: 118289

How to extract only time items from a hash?

I have a Hash like below:

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

I want the output:

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

Could anyone help me to solve this ?

Upvotes: 4

Views: 170

Answers (3)

Tilo
Tilo

Reputation: 33742

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:

  • this also allows 24-hour format times
  • this also handles the case when the hour is just one single digit

if you don't want to handle 24-hour format, then 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} 

Upvotes: -2

megas
megas

Reputation: 21791

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}

Upvotes: 6

Christian-G
Christian-G

Reputation: 2361

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 far as 'perfect' regex goes, check the regex war in the other answers comments ;)

Upvotes: 0

Related Questions