私は以下のようなハッシュを持っています:
{"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}