Because what you wrote down isn't valid Ruby code.
Strings are ordered lexicographically by default. That is, the
characters are compared one by one. This makes the string "a10" smaller
than "a2", because the character "1" is smaller than "2" (the rest of
the string is ignored).
If you want to change this behavious, you have to provide your own
sorting rule:
b.sort_by! {|s| s[/\d+/].to_i}
Each element is passed to the block and then the block values are
compared. In this case, the elements are compared by the "indices".
I found for some types of large sorts, I have better luck breaking things up, It also gives me the flexibility to do multiple types of sorts on the same data (I have one script for sorting chip ball maps where we need to do alpha sorts and then pin number sorts, so I use a routine similar to this:
class Map <
Struct.new(:char_alpha, :char_numb)
end
puts b # to display results only, not really needed.
···
On Mar 27, 2012, at 4:04 AM, Jan E. wrote:
Strings are ordered lexicographically by default. That is, the
characters are compared one by one. This makes the string "a10" smaller
than "a2", because the character "1" is smaller than "2" (the rest of
the string is ignored).
If you want to change this behavious, you have to provide your own
sorting rule:
The cool thing is you can now do all kinds of multi sorts using this type of arrangement. Comes in handy where you have to sort multiple arrays and then merge those results at the end.
The code is syntactically valid. And if all a1, a2 etc. are local
variables or methods then this code will even execute properly.
There are no commas, which doesn't work for normal array literals. Also
the question wouldn't make sense if a1, a2, ... were local variables or
methods.
The code is syntactically valid. And if all a1, a2 etc. are local
variables or methods then this code will even execute properly.
There are no commas, which doesn't work for normal array literals. Also
the question wouldn't make sense if a1, a2, ... were local variables or
methods.