【问题标题】:simple logic finding closest upcoming day of the week using Ruby使用 Ruby 查找一周中最近一天的简单逻辑
【发布时间】:2014-07-11 07:42:55
【问题描述】:

我有一个数组days,其中星期几是数字。 0 = 星期日,1 = 星期一,等等。

days = [0, 1, 3, 4] # this is just an example, the list is dynamic, it could be any combination of days (non repeating)

鉴于今天是 6(星期六),我如何确定与今天日期相对的下一个最接近的日子? (例如 0,星期日)

目前我正在这样做:

if days.include?(Date.today.wday)
  quiz_day = Date.today.wday
elsif days.include?(Date.today.wday+1)
  quiz_day = Date.today.wday+1
elsif days.include?(Date.today.wday+2)
  quiz_day = Date.today.wday+2
...
else
  quiz_day = days.first
end

哪个有效,我只是想知道是否有更简单的解决方案让我眼前一亮。

【问题讨论】:

  • 你能给出完整的图片吗?我不明白......你想达到什么目的?
  • 试试这个day_number = (0..6).find { |number| number == Date.today.wday }然后Date.today.wday + day_number
  • 我们每周都会举办一些活动,但有些日子我们没有。我正在尝试找到一种方法来查找下一个即将到来的日期,该日期具有与一周中的当前日期相关的事件。

标签: ruby arrays ruby-2.0


【解决方案1】:

Selects今天最低>=,否则first

def next_quiz_day quiz_days
   quiz_days.select{ |day| day >= Date.today.wday }.min || quiz_days.first
end   

假设一个正确的 (0..6) 并排序 quiz_days 数组。

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 2019-06-06
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2012-03-02
    相关资源
    最近更新 更多