【问题标题】:Ruby, check if date is a weekend?Ruby,检查日期是否是周末?
【发布时间】:2012-08-11 11:45:49
【问题描述】:

我的 rails 应用程序中有一个 DailyQuote 模型,其中包含股票的日期价格。已为此模型捕获数据库中的数据,包括周末。周末价格值已设置为 0。

我想将周六和周日的所有周末价格更改为周五的价格。在 Ruby 中执行此操作的最佳方法是什么?要确定日期是在星期六还是星期日,并将其值更改为该周末的星期五?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

TFM 展示了一种识别星期几的有趣方法:

t = Time.now
t.saturday?    #=> returns a boolean value
t.sunday?      #=> returns a boolean value

【讨论】:

  • 其实 Rails 提供了on_weekend? 方法。 Time.now.on_weekend? #=> true if saturday or sunday 另外,on_weekday? 则相反。
【解决方案2】:

最简单的方法:

today = Date.today

if today.saturday? || today.sunday? 
  puts "Today is a weekend!"
end

您也可以在一周中的任何其他日子执行此操作。 Ruby 非常棒,并且提供了很多这样的酷方法。我建议当你被难倒时,通过运行.methods 来查看课程可用的内容。因此,如果您运行 Date.today.methods,您将看到这些可用。

【讨论】:

    【解决方案3】:
    require 'date'
    today = Date.today
    ask_price_for = (today.wday == 6) ? today - 1 : (today.wday == 0) ? today - 2 : today
    

    require 'date'
    today = Date.today
    ask_price_for = (today.saturday?) ? today - 1 : (today.sunday?) ? today - 2 : today  
    

    ask_price_for 现在保存了您想要询问价格的日期。

    获取与您的日期相对应的实际价格取决于您的模型和您的 ORM 库(即 ActiveRecord)。

    【讨论】:

    • 如果你使用rails,@tsundoku 的回答会更好
    • 哪种方式更好?因为它使用时间而不是日期? (这与rails没有任何关系)。 saturday?sunday? 也在这里使用。
    • 抱歉,不够专心
    • 您可以为此执行Date.today.on_weekend?
    【解决方案4】:
    class Time
      def is_weekend?
        [0, 6, 7].include?(wday)
      end
    end
    
    time = Time.new
    
    puts "Current Time : " + time.inspect
    puts time.is_weekend?
    

    【讨论】:

    • 星期日可以是 7 或 0。我可能会将其更改为 [0, 6, 7].include?(wday)
    • 这个答案相当准确。让我想知道在哪里添加代码来扩展 Ruby 类。
    • 就像我在回答中所做的那样,通过使用关键字 class 您创建一个类,但如果 R​​uby 已经知道该类中的方法,您还可以扩展或覆盖该类中的方法。在这种情况下是_周末?是普通类 Time 中不存在的方法,因此该方法从代码中的该点扩展了原始类
    【解决方案5】:

    从 Rails v5 开始:

    Date.current.on_weekend?
    

    参考资料:

    【讨论】:

      【解决方案6】:

      Date.today.instance_eval { 星期六? ||星期日? }

      【讨论】:

      • 周末和节假日我用同样的方法Date.today.instance_eval { saturday? || sunday? || holiday?(:it) }
      【解决方案7】:

      在 ruby​​ 的两个日期范围内检查周末(星期六和星期日)

       weekend_days = [0,6]
       if (start_date.to_date..end_date.to_date).to_a.select {|k| weekend_days.include?(k.wday)}.present?
          # you code
       end
      

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
      猜你喜欢
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 2014-06-13
      相关资源
      最近更新 更多