I’ve got a array that I need sorted in a certain way and I’m struggling
to figure out how to make it happen the way I want.
Basically the array needs to be sorted like this:
[A, B, C, AA, AB, AF ]
that is, a single alpha character before it sorts the next character.
However, what I end up with when I sort is:
[A, AA, AB, AF, B, C]
How would I sort A to Z then AA-ZZ?
Wayne
array.sort_by {|s| [s.size, s]}
On Nov 1, 11:34pm, Isaac S. [email protected] wrote:
end
You should probably try the code you’re providing as a solution. That
cuts down on the stuff that a) raises exceptions, and b) doesn’t solve
the problem even when the exceptions are gone.
Errr, yah. I almost had it there. sry, I was doing calc hw, and saw the
message, the thought didn’t process…
On Tue, Nov 1, 2011 at 11:49 PM, Yossef M.
[email protected]wrote:
end
end
You should probably try the code you’re providing as a solution. That
cuts down on the stuff that a) raises exceptions, and b) doesn’t solve
the problem even when the exceptions are gone.
–
-yossef
–
Sincerely,
Isaac S.
Section C-4B Vice Chief, Order of the Arrow
Vice Chief of Administration, Tecumseh #65
Eagle Scout
On Nov 1, 2011, at 10:28 PM, Jan wrote:
array.sort_by {|s| [s.size, s]}
Wow, thanks Jan that was it
Wayne
arr.sort do |x,y|
if x.length < y.length
return 1
elsif x.length > y.length
return -1
else
x <=> y
end
end
On Tue, Nov 1, 2011 at 11:21 PM, Wayne B.
[email protected]wrote:
[A, AA, AB, AF, B, C]
How would I sort A to Z then AA-ZZ?
Wayne
–
Sincerely,
Isaac S.
Section C-4B Vice Chief, Order of the Arrow
Vice Chief of Administration, Tecumseh #65
Eagle Scout
On Nov 1, 2011, at 10:28 PM, Jan wrote:
array.sort_by {|s| [s.size, s]}
That’s an incredibly elegant solution, thanks for sharing!
On Wed, Nov 2, 2011 at 12:28 PM, Sam R. [email protected] wrote:
On Nov 1, 2011, at 10:28 PM, Jan wrote:
array.sort_by {|s| [s.size, s]}
That’s an incredibly elegant solution, thanks for sharing!
In case you find the temporary structure created for sorting inelegant
you can do this:
irb(main):006:0* a = %w{A AA AB AF B C}
=> [“A”, “AA”, “AB”, “AF”, “B”, “C”]
irb(main):007:0> a.sort {|x,y| (x.length <=> y.length).nonzero? or x <=>
y}
=> [“A”, “B”, “C”, “AA”, “AB”, “AF”]
Kind regards
robert