Skip to content

Instantly share code, notes, and snippets.

@kbaird
Created February 14, 2009 01:40
Show Gist options
  • Save kbaird/64213 to your computer and use it in GitHub Desktop.
Save kbaird/64213 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# liberal_sort_by.rb
class Array
def liberal_sort
liberal_sort_by { |x| x }
end
def liberal_sort_by(&block)
pertains, others = partition(&block)
pertains.sort_by(&block) + others
end
end
if (__FILE__ == $0)
require "rubygems"
require "spec"
LIST = [0, 1, 2, nil]
SORT_CRITERION = lambda { |x| x }
RAND_CRITERION = lambda { |x| rand }
describe Array do
describe "liberal_sort" do
it "should sort a reversed list, putting nil comparisons at the end" do
LIST.reverse.liberal_sort.should == LIST
end
it "should sort a shuffled list, putting nil comparisons at the end" do
shuffled_list = LIST.sort_by(&RAND_CRITERION)
shuffled_list.liberal_sort.should == LIST
end
end
describe "liberal_sort_by with criterion { |x| x }" do
it "should sort a reversed list, putting nil comparisons at the end" do
LIST.reverse.liberal_sort_by(&SORT_CRITERION).should == LIST
end
it "should sort a shuffled list, putting nil comparisons at the end" do
shuffled_list = LIST.sort_by(&RAND_CRITERION)
shuffled_list.liberal_sort_by(&SORT_CRITERION).should == LIST
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment