Ruby sort based on predefined list
I have an array objects
. Each object has an attribute that we will name display_name
.
I want to sort this array based on a predefined list of values.
So, if the predefined list looks something like this: ["Ball", "Cat", "Helicopter", "France"]
Then the objects with display_name attribute matching "Ball"
will be at the head of the list, those with the "Cat"
second in the list, etc. etc.
source to share
You can use Enumerable # sort_by :
list = ["Ball", "Cat", "Helicopter", "France"]
elements = [{:display_name => 'Cat'}, {:display_name => 'Unknown'}, {:display_name => 'Ball'}]
# sort by index in the list. If not found - put as last.
elements.sort_by { |e| list.index(e[:display_name]) || list.length }
# => [{:display_name=>"Ball"}, {:display_name=>"Cat"}, {:display_name=>"Unknown"}]
source to share
You should be able to do something like:
require 'ostruct'
list = %w{Ball Cat Helicopter France}
items = [
OpenStruct.new(:display_name => 'Helicopter'),
OpenStruct.new(:display_name => 'France'),
OpenStruct.new(:display_name => 'Ball'),
OpenStruct.new(:display_name => 'Cat'),
]
items.sort { |x,y| list.index(x.display_name) <=> list.index(y.display_name) }
Note, this is not deterministic if you have multiple items with the same display name.
source to share