Ruby,检查日期是否是周末?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11914422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:50:46  来源:igfitidea点击:

Ruby, check if date is a weekend?

ruby-on-railsrubyruby-on-rails-3

提问by General_9

I have a DailyQuote model in my rails application which has a dateand pricefor a stock. Data in the database has been captured for this model including weekends. The weekend price values have been set as 0.

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

I want to change all the weekend prices for Saturday and Sunday to whatever the price was on Friday. What is the best way to do this in Ruby? To identify if a date falls on a Sat or Sun and change its value to the Fri of that weekend?

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

采纳答案by robustus

require 'date'
today = Date.today
ask_price_for = (today.wday == 6) ? today - 1 : (today.wday == 0) ? today - 2 : today

or

或者

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

ask_price_fornow holds a date for which you would want to ask the price for.

ask_price_for现在有一个您想要询问价格的日期。

Getting the actual price which is corresponding to you date depends on your Model and your ORM-Library (i.e. ActiveRecord).

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

回答by tsundoku

TFMshows an interesting way to identifying the day of the week:

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

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

回答by heading_to_tahiti

The simplest approach:

最简单的方法:

today = Date.today

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


You can also do this for any other day of the week. Ruby is fantastic and offers a lot of cool methods like this. I suggest when you get stumped take a look at what's available to the class by running .methodson it. So if you run Date.today.methodsyou will see these available.

您也可以在一周中的任何一天执行此操作。Ruby 非常棒,并提供了很多像这样很酷的方法。我建议当你遇到困难时,通过运行来看看类可以.methods使用什么。因此,如果您运行,Date.today.methods您将看到这些可用。

回答by peter

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

time = Time.new

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

回答by cafe_

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

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