4

我有一个像下面这样的哈希:

{"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}

谁能帮我解决这个问题?

4

3 回答 3

6
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}
于 2013-04-16T21:13:04.343 回答
0
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}

就“完美”正则表达式而言,请检查其他答案评论中的正则表达式战争;)

于 2013-04-16T20:48:45.240 回答
-2

更一般的方法:

 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 小时格式时间
  • 这也处理小时只是一位数的情况

如果您不想处理 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} 
于 2013-04-16T20:45:18.560 回答