我有一個哈希象下面這樣:如何從哈希中僅提取時間項?
{"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}
我很欣賞使用Time.strptime – christianblais
這實際上是不好的 - 因爲這種方式你只需要一個特定的時間格式 – Tilo
更通用的方法:
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}
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}
至於 '完美' 的正則表達式去,檢查其他答案評論正則表達式的戰爭;)
爲什麼downvote沒有評論?如果這個答案是錯誤的,我將不勝感激:) –
我提高了你,只是爲了抵消downvote。我也很感激關於downvotes的反饋。 – christianblais
出於好奇 - 你爲什麼使用這樣一個奇怪的散列 – Noz
@Cyle很好的問題。我需要它在頁面上使用'nokogiri'時做出一些輸出['tensports'](http://www.tensports.com/schedule.php) –
是否解決了您的問題? – Tilo