From: Ian Macdonald Date: 2002-08-07T08:54:47+09:00 Subject: sort problem Hi, I have a file with data like this: ina1 ina15 inb12 ina9 inc10 inda12 inef14 inab14 inzz8 inzz80 inzz9 etc. I want to sort it alphabetically on the first part of the string, then numerically on the second part. The sorted file should look like this: ina1 ina9 ina15 inab14 inb12 inc10 inda12 inef14 inzz8 inzz9 inzz80 However, I can't seem to write the Ruby code to do this properly. Having written the Perl to do this kind of thing many times before, I set about writing it in Perl and sure enough, the Perl version works. The Ruby code is so analagous that I just can't see where I'm going wrong. Here are the two versions: Perl ---- undef $/; @foo = sort { ($c,$d) = ($a =~ /^([a-z]+)([0-9]+)$/); ($e,$f) = ($b =~ /^([a-z]+)([0-9]+)$/); $c cmp $e or $d <=> $f} split(/\n/, <>); print join "\n", @foo' Ruby ---- $/ = nil foo = gets.split("\n") r = /^([a-z]+)([0-9]+)$/ foo = foo.sort {|a,b| c,d = r.match(a)[1,2] e,f = r.match(b)[1,2] c <=> e or d.to_i <=> f.to_i} puts foo The Ruby version outputs this: ina1 ina15 ina9 inab14 inb12 inc10 inda12 inef14 inzz80 inzz8 inzz9 which shows that the numeric comparison on the second part of the string is clearly not working, leading me to suspect that the <=> operator doesn't work with objects of type Fixnum, but according to the docs, it gets mixed in from Comparable. So, what's wrong with the Ruby code? This is Ruby 1.6.7, in case that matters. Ian -- Ian Macdonald | Somewhere in Tenafly, New Jersey, a ian@caliban.org | chiropractor is viewing "Leave it to | Beaver"! | |