我对 Ruby 很陌生,我正在尝试扩展 Date 类以添加一个函数,该函数将返回该月的第一个星期日。这是为了帮助绘制月历。所以说九月从星期六开始。然后我希望这个函数返回 8 月 26 日,因为那是日历需要首先绘制的日期。
我在 irb 有这个工作:
fs = Date.today - Date.today.mday + 1
fs = fs - fs.wday
所以现在我正在尝试将日期类扩展为
class Date
def first_of_month
return Date.new(self.year, self.month, 1)
end
def first_sunday_of_first_week
return self.first_of_month - self.wday
end
end
第一个月的方法似乎工作正常。这个月的第一个星期日没有。我认为这与 Date.new 丢失有关,但无论我如何尝试重做它似乎都不起作用。我正在制作一个 Sinatra 应用程序,所以我没有执行此操作的 rails 功能。
此处的函数为这两种方法返回每月的第一天,而不是返回每月的第一个星期日。
我如何正确地使这种扩展方法起作用?谢谢
更新:
class Date
def first_of_month
return Date.new(self.year, self.month, 1)
end
def first_sunday_of_first_week
first_of_month - first_of_month.wday
end
end
这似乎可行,但它是正确的还是我强迫的工作比需要的多。这不是创建到 Date.new 的返回一个吗?