Skip to content

Instantly share code, notes, and snippets.

@jamster
Created January 30, 2009 17:05
Show Gist options
  • Save jamster/55145 to your computer and use it in GitHub Desktop.
Save jamster/55145 to your computer and use it in GitHub Desktop.
require "rubygems"
require "activesupport"
class Person
attr_accessor :name, :age
def initialize(name, age)
@name=name
@age=age
end
end
class Array
def sort_by_list(ordered_list, &block)
new_ol = ordered_list.inject({}){|new_hash, sort_item| new_hash[sort_item] = ordered_list.index(sort_item); new_hash}
sorted = self.map{|item| [item, new_ol[block.call(item)] || 0]}.sort_by{|cred| cred[1]}.map{|cred| cred[0]}
end
end
my_list = [
Person.new("Jason", "30"),
Person.new("Josh", "28"),
Person.new("Ross", "27"),
Person.new("Danny", "27"),
Person.new("Pat", "23")
]
sort_list = ["Josh", "Jason", "Danny", "Pat", "Ross"]
sorted_list = my_list.sort_by_list(sort_list) do |item|
item.name
end
puts my_list.to_yaml
puts sorted_list.to_yaml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment