rails helper function to return the most recent date
ruby, ruby-on-rails, ruby-on-rails-3, ruby-on-rails-3.1
Solution
The `.max` method will do it for you ;)
> [Date.today, (Date.today + 2.days) ].max
#=> Fri, 05 Jul 2013
Documentation about it (Ruby 2.0):
- http://ruby-doc.org/core-2.0/Enumerable.html#method-i-max
You may need to parse the data into Dates, if they are strings, you can use:
dates = ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
dates = dates.map{ |date_str| Date.parse(date_str) }
dates.max #=> returns the maximum date of the Array
See in my irb console (Ruby 1.9.3):
> dates = ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
#=> ["2012-10-10T22:11:52.000Z", "2012-11-10T22:11:52.000Z", "2013-10-10T22:11:52.000Z"]
> dates = dates.map{ |date_str| Date.parse(date_str) }
#=> [Wed, 10 Oct 2012, Sat, 10 Nov 2012, Thu, 10 Oct 2013]
> dates.max
#=> Thu, 10 Oct 2013
(use `DateTime.parse(date_str)` if you want to keep the Time also)
Problem
I need to Write rails helper method to return the most recent date. So far this is my method ``` def latest_date(value_dates) value_dates.each |value_date| do my_dates << value_date end ``` I need to sort the above array and return just the latest date. The date is in the following format: ``` 2012-10-10T22:11:52.000Z ``` Is there a sort method for date?