Reputation: 29
I need help getting the date out of strings in an array then sorting those strings by the date. This is the array with each strings index number.
array = [
[0] "Bonk Radek S Male Green 6/3/1978",
[1] "Bouillon Francis G Male Blue 6/3/1975",
[2] "Smith Steve D Male Red 3/3/1985"
]
I want to re-arange and sort each string by the date in ascending order. Anyone have a clean and simple way of doing this in ruby?
Upvotes: 1
Views: 55
Reputation: 110675
You could write it like so:
array = [
"Bonk Radek S Male Green 6/3/1978",
"Bouillon Francis G Male Blue 6/3/1975",
"Thornton Billy-Bob Male Purple 11/3/1985",
"Smith Steve D Male Red 3/3/1985",
"Dillon Matt Male Orange 14/11/1984"
]
def year_month_day(line)
d, m, y =
line.scan(/([1-9]|[1-3]\d)\/([1-9]|1[0-2])\/([12]\d{3})/).flatten
[y.to_i, m.to_i, d.to_i]
end
array.sort_by { |line| year_month_day(line) }
# => ["Bouillon Francis G Male Blue 6/3/1975",
# "Bonk Radek S Male Green 6/3/1978",
# "Dillon Matt Male Orange 14/11/1984",
# "Smith Steve D Male Red 3/3/1985",
# "Thornton Billy-Bob Male Purple 11/3/1985"]
Upvotes: 0
Reputation: 118261
You can do
require 'date'
array = [
"Bonk Radek S Male Green 6/3/1978",
"Bouillon Francis G Male Blue 6/3/1975",
"Smith Steve D Male Red 3/3/1985"
]
array.map { |str| str[/\d+\/\d+\/\d+/] }
# => ["6/3/1978", "6/3/1975", "3/3/1985"]
array.map { |str| Date.strptime(str[/\d+\/\d+\/\d+/], "%d/%m/%Y") }
# => [#<Date: 1978-03-06 ((2443574j,0s,0n),+0s,2299161j)>,
# #<Date: 1975-03-06 ((2442478j,0s,0n),+0s,2299161j)>,
# #<Date: 1985-03-03 ((2446128j,0s,0n),+0s,2299161j)>]
# to sort
array.sort_by { |str| Date.strptime(str[/\d+\/\d+\/\d+/], "%d/%m/%Y") }
# => ["Bouillon Francis G Male Blue 6/3/1975",
# "Bonk Radek S Male Green 6/3/1978",
# "Smith Steve D Male Red 3/3/1985"]
Upvotes: 1