2013-03-14 73 views
2

我的工作是應該確定基於日期範圍當年的「季節」的腳本:紅寶石確定季(秋,冬,春季或夏季)

例如:

January 1 - April 1: Winter 
April 2 - June 30: Spring 
July 1 - September 31: Summer 
October 1 - December 31: Fall 

我不知道如何最好的方式(或最好的紅寶石方式)去做這件事。其他人碰到如何做到這一點?

+1

您不應該考慮腳本是在北半球還是在南半球? – 2013-03-14 16:42:53

+0

這是一個cron作業,將在我的一臺服務器上運行,所以我知道它會跑 – dennismonsewicz 2013-03-14 17:20:21

+0

大多數地方定義夏天的3最熱的月份和冬季最冷3。如果您從您的個人資料中表明您的位置開始運行它,那麼您需要將其向左移動1個月。 – iain 2013-03-14 17:39:24

回答

6

9月31日?

作爲leifg建議的,在這裏它是在代碼:

require 'Date' 

class Date 

    def season 
    # Not sure if there's a neater expression. yday is out due to leap years 
    day_hash = month * 100 + mday 
    case day_hash 
     when 101..401 then :winter 
     when 402..630 then :spring 
     when 701..930 then :summer 
     when 1001..1231 then :fall 
    end 
    end 
end 

一旦定義,例如稱之爲像這樣:

d = Date.today 
d.season 
+0

哇,這太棒了!我一整個早上都在玩這個。非常感謝! – dennismonsewicz 2013-03-14 17:34:34

+1

更好地利用'一個月* 100 + mday',將是快10倍 – 2013-06-07 20:13:33

+0

@ zed_0xff:是的,其實我測量它200X關於Ruby 1.9.3更快,所以我更新了答案。謝謝 – 2013-06-08 12:07:43

1

沒有範圍。

require 'date' 

    def season 
     year_day = Date.today.yday().to_i 
     year = Date.today.year.to_i 
     is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 
     if is_leap_year and year_day > 60 
     # if is leap year and date > 28 february 
     year_day = year_day - 1 
     end 

     if year_day >= 355 or year_day < 81 
     result = :winter 
     elsif year_day >= 81 and year_day < 173 
     result = :spring 
     elsif year_day >= 173 and year_day < 266 
     result = :summer 
     elsif year_day >= 266 and year_day < 355 
     result = :autumn 
     end 

     return result 
    end