On Oct 30, 10:35 am, Tim F. [email protected] wrote:
I have an array of strings like so:
Tuesday 12:00 AM
Sunday 9:00 AM
Tuesday 3:00 PM
Friday 7:30 AM
Wednesday 5:00 PM
and I want the array sorted by day name and then time. Is it possible to
do this without resorting to a two stage process?
Although you already have better answers specific to your needs, the
answer to this question is also yes:
class Array; def rand; self[ Kernel.rand(length) ]; end; end
Person = Struct.new( :first, :last, :age ) do
def to_s; “#{last}, #{first} - #{age}”; end
end
FIRSTS = %w[ Gavin Lisa John Joe Jim Jill Bob Anne Zach Michael ]
LASTS = %w[ Jones Smith Jackson ]
people = (0…40).map{ Person.new( FIRSTS.rand, LASTS.rand, rand
(60) ) }
Name ascending, age descending
puts people.sort_by{ |who| [ who.last, who.first, -who.age ] }
#=> Jackson, Anne - 28
#=> Jackson, Anne - 22
#=> Jackson, Bob - 29
#=> Jackson, Bob - 9
#=> Jackson, Gavin - 54
#=> Jackson, Jim - 12
#=> Jackson, Jim - 9
#=> Jackson, Jim - 1
#=> Jackson, Joe - 47
#=> Jackson, John - 41
#=> Jackson, Lisa - 8
#=> Jackson, Zach - 38
#=> Jones, Anne - 52
#=> Jones, Bob - 48
#=> Jones, Bob - 15
#=> Jones, Bob - 6
#=> Jones, Gavin - 30
#=> Jones, Jill - 35
#=> Jones, Jim - 50
#=> Jones, Jim - 49
#=> Jones, Jim - 44
#=> Jones, Jim - 3
#=> Jones, Joe - 35
#=> Jones, Joe - 11
#=> Jones, Joe - 4
#=> Jones, John - 37
#=> Jones, John - 10
#=> Jones, Zach - 21
#=> Jones, Zach - 2
#=> Smith, Anne - 20
#=> Smith, Bob - 48
#=> Smith, Gavin - 4
#=> Smith, Jill - 56
#=> Smith, Jill - 39
#=> Smith, Jill - 25
#=> Smith, Jill - 2
#=> Smith, Jim - 7
#=> Smith, Joe - 49
#=> Smith, John - 44
#=> Smith, John - 29
#=> Smith, John - 28