Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A special kind of sorting algorithm, where "Other" has to be the last item when sorted
require 'ostruct'
module SortWithOther
def <=>(other)
if self.send(sort_field).downcase == "Other".downcase
1
elsif other.send(sort_field).downcase == "Other".downcase
-1
else
self.send(sort_field) <=> other.send(sort_field)
end
end
end
class Person
include SortWithOther
#sort_with_other :name, "Other"
attr_accessor :name
def initialize(name)
@name = name
end
def sort_field
:name
end
end
class Animal
include SortWithOther
#sort_with_other_attr :name, "Crap"
attr_reader :nickname
def initialize(nickname)
@nickname = nickname
end
def sort_field
:nickname
end
end
describe SortWithOther do
it "sorts a collection of Person objects" do
people = [ Person.new("Nate"), Person.new("Victor"), Person.new("Attila"), Person.new("Other")]
people.sort!
people.first.name.should == "Attila"
people.last.name.should == "Other"
end
it "sorts a collection of Animal objects" do
animals = [ Animal.new("Nate"), Animal.new("Victor"), Animal.new("Attila"), Animal.new("Other")]
animals.sort!
animals.first.nickname.should == "Attila"
animals.last.nickname.should == "Other"
end
it "sorts an OStruct" do
objects = [OpenStruct.new(:name => "Nate"), OpenStruct.new(:name => "Attila")]
objects.each do |person_object|
person_object.extend(SortWithOther)
class << person_object
def sort_field
:name
end
end
end
objects.sort!
objects.first.name.should == "Attila"
objects.last.name.should == "Nate"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment