我有一个像下面这样的哈希:
{"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e}
我想要输出:
作为{"5:00 PM" => :d,"09:25 PM" => :e}
谁能帮我解决这个问题?
我有一个像下面这样的哈希:
{"19th Apr, 2013" => :a, "20th Apr, 2013" => :b,"Tomorrow" => :c,"5:00 PM" => :d,"09:25 PM" => :e}
我想要输出:
作为{"5:00 PM" => :d,"09:25 PM" => :e}
谁能帮我解决这个问题?
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}
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/ }
给你:
{"5:00 PM"=>:d, "09:25 PM"=>:e}
就“完美”正则表达式而言,请检查其他答案评论中的正则表达式战争;)
更一般的方法:
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}
笔记:
如果您不想处理 24 小时格式,请使用:
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}