Ruby trick – Save a sort for later, Reuse a sort block

I want to use the sort method on an array with a given block, then reuse it a few times.  I don’t want to create a separate method for it and I don’t want to repeat the block for each sort.

sorter = lambda{ |a,b| a <=> b }
[1,2,3,4,5,6].sort &sorter
[6,5,4,3,2,1].sort &sorter

or use a Proc.new

sorter = Proc.new { |a,b| a <=> b}
[1,2,3,4,5,6].sort &sorter
[6,5,4,3,2,1].sort &sorter

Posted on March 29, 2009 at 12:09 pm by Jordan Carter · Permalink
In: Uncategorized · Tagged with: , , , ,

Leave a Reply