Wednesday, March 11, 2009

When sorting complex structures in Perl is is common to use syntax like:

sort { $lname{$a} <=> $lname{$b} || $fname{$a} <=> $fname{$b} } @names

The Perl sort documentation lists examples with this syntax. True to form the Ruby sort documentation doesn't show examples of anything that complex. Best I can tell anything like this doesn't work in Ruby:

a <=> b || c <=> d

Any way I write that I get back the result of the first comparison, even if the result is zero (which should trigger a fall-through to the second comparison).

Since Ruby's Array implements <=> you can achieve the desired result with:

[a, c] <=> [b, d]

No comments: