Ruby, check if date is a weekend?

2020-05-20 02:59发布

问题:

I have a DailyQuote model in my rails application which has a date and price for a stock. Data in the database has been captured for this model including weekends. The weekend price values have been set as 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?

回答1:

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_for now holds a date for which you would want to ask the price for.

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



回答2:

TFM shows an interesting way to identifying the day of the week:

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


回答3:

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 .methods on it. So if you run Date.today.methods you will see these available.



回答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?


回答5:

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