1

I'm developing a tournament bracketing app and need to compare some dates together in order to place them in their designated age group. I can't seem to figure out how I would write something like this.

6 - under = 2007-09-01 to present
8 - under = 2005-09-01 to 2007-08-31
10 - under = 2003-09-01 to 20050831

Would it be something like this? and is there a better way to compare the dates to each other.

def age_group
    if self.dob <= 20030901
        "10"
    elsif self.dob <= 20050901
        "8"
    else self.dob <= 20070901
        "6"
    end
end

Thank you

andrew ng
  • 11
  • 1

3 Answers3

3

You can certainly keep to your age_group method, there's nothing wrong with it. I'd just tweak it like so:

def age_group
    if self.dob <= 10.years.ago
        "10"
    elsif self.dob <= 8.years.ago
        "8"
    elsif self.dob <= 6.years.ago
        "6"
    end
end
Anthony
  • 15,435
  • 4
  • 39
  • 69
  • This won't give function as expected. Someone born 10 years ago would have a date of birth less than `6.years.ago` and will be sorted into the 6 year old category. – AJ Gregory Sep 22 '14 at 20:42
  • i guess this method will bring both 6.year and 8.year category under roof of 10.years as well ? – Rahul Dess Sep 22 '14 at 20:47
0

If you do it like this, you will have to go update the cut-off dates of birth each year. You could calculate the age instead and take it from there:

def age
  now = Time.now.utc.to_date
  now.year - birthday.year - (birthday.to_date.change(:year => now.year) > now ? 1 : 0)
end

(above from Get person's age in Ruby)

Then define the age group:

def age_group
  if self.age <= 10
    "10"
  elsif ...
etc.
Community
  • 1
  • 1
NicoFerna
  • 603
  • 3
  • 11
0

A case statement would work well for this, as it uses === for comparisons.

require 'date'

R10U = (Date.parse("2003-09-01")..Date.parse("2005-08-31"))
R8U  = (Date.parse("2005-09-01")..Date.parse("2007-08-31"))
R6U  = (Date.parse("2007-09-01")..Date.today)

def age_group(dob)
  case Date.parse(dob)
  when R6U  then "6 - under"
  when R8U  then "8 - under"
  when R10U then "10 - under"
  else raise ArgumentError, "dob = '#{dob}' is out-of-range"
  end
end

age_group("2006-04-12")
  #=> "8 - under"
age_group("2004-11-15")
  #=> "10 - under"
age_group("2011-06-01")
  #=> "6 - under"
age_group("2002-04-30")
  #=> ArgumentError: dob = '2002-04-30' is out-of-range
age_group("2015-06-01")
  #=> ArgumentError: dob = '2015-06-01' is out-of-range
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100