0

In my Rails 3.2 app, I need to create an if condition that checks what date range today's date is in. Something like this:

current_date = Date.today

# if current_date is between 2013-08-01..2013-08-15
#   return 1
# elsif current_date is between 2013-08-16..2013-08-30
#   return 2
# end
yellowreign
  • 3,528
  • 8
  • 43
  • 80
  • http://stackoverflow.com/questions/4521921/how-to-know-if-todays-date-is-in-a-date-range – Zabba Aug 22 '13 at 17:32
  • I saw that question, but how do I make that work with hard coded dates, as well as returning a value other than true/false? – yellowreign Aug 22 '13 at 17:38

2 Answers2

3

Your pseudo-code almost has it, You can just write the following using #cover:

def date_range(date)
  if (Date.new(2013, 8, 1) .. Date.new(2013, 8, 15)).cover?(date)
    1
  elsif (Date.new(2013, 8, 16) .. Date.new(2013, 8, 30)).cover?(date)
    2
  end
end
mdemolin
  • 2,514
  • 1
  • 20
  • 23
0

You can use Comparable#between?:

if current_date.between? Date.new(2013, 8, 1), Date.new(2013, 8, 15)
  1
elsif current_date.between? Date.new(2013, 8, 16), Date.new(2013, 8, 30)
  2
end

Or date ranges: (see Range#===)

case current_date
when Date.new(2013, 8, 1)..Date.new(2013, 8, 15)
  1
when Date.new(2013, 8, 16)..Date.new(2013, 8, 30)
  2
end
Stefan
  • 109,145
  • 14
  • 143
  • 218