From: Rick Bradley Date: 2002-06-03T23:42:51+09:00 Subject: ruby equivalent for perl multi-index sort? Coming from a perl background I have a lot of programs which do operations on arrays, including sorts. For example today I came across one of mine where I wrote: @filelist = map { $_->[0] . ($_->[1] ? '.'.$_->[1] : '') } sort {$a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } map { /(\d+)(?:\.(\d+))?/; [ $1, $2 || 0 ] } grep {/^\d+(?:\.\d+)?$/} readdir(INDIR); It takes a list of files, extracts the numeric ones and orders them numerically. If they have fractional parts it numbers them by treating the fractional parts as integers (don't ask why ;-). The bulk of that is easy to rewrite the Ruby way, except for the multi-index sort: sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } The spaceship returns 0 when the first pair of elements are 0 and this perl idiom takes advantage of the fact that 0 is false and therefore '||' will evaluate its second operand. It's akin to saying "if the first elements are the same then order on the second elements". In Ruby 0 isn't false so the comparable Ruby expression won't trigger the comparison on later indices. I've been wondering if there's a way to efficiently implement this idiom in Ruby. Ideas? Rick -- http://www.rickbradley.com MUPRN: 957 (82F/90F) | like being trapped in random email haiku | a video game. i woke | up thrashing around.