Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 鲁比,看看日期是不是周末?_Ruby On Rails_Ruby_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 鲁比,看看日期是不是周末?

Ruby on rails 鲁比,看看日期是不是周末?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我的rails应用程序中有一个DailyQuote模型,它有一个股票的日期和价格。数据库中的数据已为该模型捕获,包括周末。周末价格值已设置为0 我想把周六和周日的周末价格改成周五的价格。在Ruby中实现这一点的最佳方法是什么?确定某个日期是在周六还是周日,并将其值更改为该周末的周五 class Time def is_weekend? [0, 6, 7].include?(wday) end end time = Time.new puts "Current Time : "

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

我想把周六和周日的周末价格改成周五的价格。在Ruby中实现这一点的最佳方法是什么?确定某个日期是在周六还是周日,并将其值更改为该周末的周五

class Time
  def is_weekend?
    [0, 6, 7].include?(wday)
  end
end

time = Time.new

puts "Current Time : " + time.inspect
puts time.is_weekend?

ask_price_for
现在保存一个日期,您希望为该日期询价

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

显示了一种确定一周中哪一天的有趣方法:

t = Time.now
t.saturday?    #=> returns a boolean value
t.sunday?      #=> returns a boolean value
最简单的方法是:

你也可以在一周中的其他任何一天这样做。Ruby非常棒,它提供了很多像这样很酷的方法。我建议当你被难倒时,通过在类上运行
.methods
来查看类的可用性。因此,如果您运行
Date.today.methods
您将看到这些方法可用。

Date.today.instance_eval{saturday?| | sunday?}

检查两个日期之间的周末

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

Date.current.on_weekend?
参考资料:


另请参见:星期日可以是7或0。我可能会把它改成
[0,6,7]。包括?(wday)
。这个答案非常准确。让我想知道我应该在哪里添加代码来扩展Ruby类。就像我在回答中所做的那样,通过使用关键字class,您可以创建一个类,但如果Ruby知道它已经准备好了,您还可以扩展或覆盖该类中的方法。在这种情况下,你是周末吗?在正常的类时间内是一个不存在的方法,因此该方法在代码中从该点扩展了原始类如果使用rails,@tsundoku的答案更好哪种方式更好?因为它使用时间而不是日期?(这与rails无关)
saturday?
sunday?
也在这里使用。很抱歉,我没有注意到您可以执行
Date。今天。在周末?
执行此操作。实际上Rails提供了
在周末?
方法<代码>Time.now.on#u weekend?#=>如果周六或周日也是如此,
在工作日?
则相反。我对周末和假日使用相同的方法
Date.today.instance_eval{saturday?| sunday?| holiday?(:it)}
请不要只发布代码作为答案,还要解释代码的作用以及它是如何解决问题的。带有解释的答案通常更有帮助,质量更好,更容易吸引选票。
today = Date.today

if today.saturday? || today.sunday? 
  puts "Today is a weekend!"
end
weekend_days = [0,6]
if (self.start_date.to_date..self.end_date.to_date).to_a.select {|k| weekend_days.include?(k.wday)}.present?
    # you code
end
Date.current.on_weekend?