Ruby - How Many Days?

Ruby - How Many Days?

I need to calculate how many days lived on earth based on three parameters : day, month and year. I don't know how to convert the input onto a date; and then how to convert the date onto number of days. This is my code for the moment...

require 'date'
def age_in_days(day, month, year)
  lived = (day+"-"+month+"-"+year).to_s
  date_lived Date.parse(lived)
  return (Date.today - date_lived).to_i
end
1

1 Answer

You can create a Date object directly with:

Date.new(year, month, day)

There's no need to convert it to a string and parse. Parsing could also be dangerous. Is 1982-04-02 the 4th of February or 2nd of April?

You cannot add a number and string like this, BTW. Should 1 + '2' be '12' or 3? Ruby cannot decide for you so you need to explicitly convert integers to string.

day.to_s + "-" + month.to_s + "-" + year.to_s

or simply

[day, month, year].join('-')

But you don't need it anyway:

require 'date'

def age_in_days(day, month, year)
  birthdate = Date.new(year, month, day)
  (Date.today - birthdate).to_i
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.