Ruby 红宝石季节(秋季、冬季、春季或夏季)

Ruby 红宝石季节(秋季、冬季、春季或夏季),ruby,datetime,Ruby,Datetime,我正在编写一个脚本,根据日期范围确定一年中的“季节”: 例如: January 1 - April 1: Winter April 2 - June 30: Spring July 1 - September 31: Summer October 1 - December 31: Fall 我不确定如何最好的方式(或最好的ruby方式)去做这件事。其他人有没有遇到过这样做的方法?您可以尝试使用范围和日期对象: 9月31日 正如leifg所建议的,代码如下: require 'Date' cl

我正在编写一个脚本,根据日期范围确定一年中的“季节”:

例如:

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

我不确定如何最好的方式(或最好的ruby方式)去做这件事。其他人有没有遇到过这样做的方法?

您可以尝试使用范围和日期对象:

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
没有射程

  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
需要“日期”
def季节
year\u day=Date.today.yday().to\u i
年=日期。今天。年。到
是闰年=年份%4==0和年份%100!=0 | |年%400==0
如果闰年和年日>60
#如果是闰年且日期>2月28日
年日=年日-1
结束
如果年日>=355或年日<81
结果=:冬季
如果年日>=81且年日<173
结果=:弹簧
如果年日>=173且年日<266
结果=:夏季
如果年日>=266且年日<355
结果=:秋季
结束
返回结果
结束
方法很好,但对我来说,这些日期不太正确。它们显示秋天在12月31日结束,这在我能想到的任何情况下都不是这样

利用季节:

  • 春季从3月1日到5月31日
  • 夏季从6月1日到8月31日
  • 秋季(秋季)从9月1日到11月30日;及
  • 冬季从12月1日持续到2月28日(闰年的2月29日)
代码需要更新为:

require "date"

class Date
  def season
    day_hash = month * 100 + mday
    case day_hash
      when 101..300 then :winter
      when 301..531 then :spring
      when 601..831 then :summer
      when 901..1130 then :fall
      when 1201..1231 then :winter
    end
  end
end

您是否还应该考虑脚本是在北半球还是南半球运行?这是一个cron作业,将在我的一台服务器上运行,因此我知道它将在哪里运行。大多数地方将夏季定义为最热的3个月,将冬季定义为最冷的3个月。如果您是从您的个人资料显示的位置运行它,那么您希望将其向左移动1个月。您的日期不是正式的季节,并且您使用的方式比冬季从12月开始到3月结束的真实季节更容易。这就是我挂断电话的地方。哇,太棒了!我整个上午都在玩弄这个。。非常感谢!更好地使用
月*100+mday
,将是10倍faster@zed_0xff:是的,事实上,我在Ruby 1.9.3上测得的速度快了200倍,所以我正在更新答案。谢天谢地,这在实际的季节(例如,12月21日至3月20日为冬季)不起作用。知道怎么做吗?@Corey:更改case块中的数字,以匹配您希望使用的任何定义。此答案中的值与问题中的季节定义相匹配。