2

我有一个约会,例如,我想找到最近的星期四。虽然我希望它适用于任何工作日,而不仅仅是星期四。

为避免混淆,我不想要下周四,我想要上周四或下周四,以最接近的为准。所以它必须是双向的。

我已经编写了一个代码,但我显然对 while 循环不满意,我想知道你们是否有更好的实现的想法。

def closest_date(date, wday)

  # already ok
  return date if date.wday == wday

  before_date = date
  after_date = date

  until before_date.wday == wday && after_date.wday == wday
    before_date -= 1.day unless before_date.wday == wday
    after_date += 1.day unless after_date.wday == wday
  end

  if (date - before_date).to_i > (after_date - date).to_i
    return after_date
  else
    return before_date
  end

end
4

2 回答 2

3

这是我要做的:

def closest_day(weekday_name,date=Date.today)
  distance = Date.parse(weekday_name).cwday - date.cwday
  (date + (distance.abs < 4 ? distance : 7 - distance.abs).days)
end

weekday_name例如,“ ”在哪里thursday

于 2013-06-27T09:15:14.253 回答
1
def closest_date(date, wday)
  distance = wday - date.wday
  date + distance.days
end
于 2013-06-26T19:20:53.040 回答