Reputation: 118289
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
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:
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
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
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