Reputation: 227
I have an array of strings which I want to sort so I get the latest one using ruby
Each string is made up a datestamp, a file size and an ipaddress
["09/Feb/2012:12:56:40.009+0000 13894 10.0.0.1",
"09/Feb/2012:14:45:03.829+0000 12951 10.0.0.1",
"09/Feb/2012:15:13:07.722+0000 3812 10.0.0.1",
"09/Feb/2012:15:18:47.813+0000 50290 10.0.0.1",
"09/Feb/2012:15:18:55.430+0000 2796 10.0.0.1",
"09/Feb/2012:16:02:13.494+0000 5193 10.0.0.1",
"09/Feb/2012:16:17:18.661+0000 4523 10.0.0.1",
"09/Feb/2012:16:59:50.671+0000 9764 10.0.0.1",
"09/Feb/2012:17:07:55.129+0000 3944 10.0.0.1"]
What I need to do is capture the string with the latest datestamp (09/Feb/2012:17:07:55.129 in the example above)
I can’t always assume that the array will be in date order so just using array.last won’t work
Anyone got any ideas?
Upvotes: 0
Views: 245
Reputation: 44110
require 'date'
a.max_by{|e| DateTime.strptime(e.split(' ').first, '%d/%b/%Y:%H:%M:%S.%L%z')}
#=> "09/Feb/2012:17:07:55.129+0000 3944 10.0.0.1"
Upvotes: 2
Reputation: 5231
I'd first create a new array of only the date strings. I'd then sort and ask for the last element in the array.
values = #your array of strings
latest_date = values.map{|d| d.split(' ')[0]}.sort.last
Upvotes: 0