如何比较Ruby中的月份组合?

时间:2016-10-11 15:42:19

标签: ruby date comparison monthcalendar

我正在使用Rails 4.2.7。我有两对数字......

month1   # A number between 1 and 12
year1    # a four digit year
month2   # A number between 1 and 12
year2    # A four digit year

如何编写比较表达式以确定“month2-year2”组合是否大于或等于“month1-year1”组合?例如,如果month2 = 1,year2 = 2017,month1 = 12,year1 = 2016,则month2-year2组合大于month1-year1组合。

2 个答案:

答案 0 :(得分:2)

month1, month2, year1, year2 = 12, 1, 2016, 2017
=> [12, 1, 2016, 2017]
Time.new(year1, month1) >= Time.new(year2, month2)
=> false
Time.new(year2, month2) >= Time.new(year1, month1)
=> true

参考:https://ruby-doc.org/core-2.2.0/Time.html#class-Time-label-Creating+a+new+Time+instance

答案 1 :(得分:1)

这非常简单,无需创建日期或时间对象。

def first_smaller?(ym1, ym2)
  (ym1 <=> ym2) == -1
end

first_smaller? [2016,12], [2017,1]
  #=> true
first_smaller? [2017,1], [2016,12]
  #=> false
first_smaller? [2017,1], [2017,1]
  #=> false

请参阅Array#<=>文档的第三段,了解Ruby如何命令数组。

如果您还想知道两个数组是否相等,您可以编写如下内容:

def ordering(ym1, ym2)
  case ym1 <=> ym2
end

如果-1较小则返回ym1+1如果ym2较小则返回0,如果数组相等则返回 protected void Application_BeginRequest(object sender, EventArgs e) { if (Context.Request.Path.Contains("odata/")) { Context.Response.AddHeader("Access-Control-Allow-Origin", "*"); Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST PUT, DELETE, OPTIONS"); Context.Response.AddHeader("Access-Control-Allow-Credentials", "true"); } }