Skip to content

Instantly share code, notes, and snippets.

@kjlape
Last active June 14, 2019 17:26
Show Gist options
  • Select an option

  • Save kjlape/4a3f0cd065161fd57d9587021aa8cbf7 to your computer and use it in GitHub Desktop.

Select an option

Save kjlape/4a3f0cd065161fd57d9587021aa8cbf7 to your computer and use it in GitHub Desktop.
Sorting lists with lists in ruby
# Given #1: a list of ids in a specific order you want to preserve
ordered_ids = (1..3).to_a.reverse
#=> [3, 2, 1]
indexed_ids = ordered_ids.each_with_index.to_h
#=> {3=>0, 2=>1, 1=>2}
# Given #2: a collection of items with the same ids as in the list above, but in no particular order
# Example: `Model.where(…)` in rails
Model = Struct.new(:id, :name)
items = (1..3).map { |id| Model.new(id, "Item #{id}") }
#=> [#<struct Model id=1, name="Item 1">, #<struct Model id=2, name="Item 2">, #<struct Model id=3, name="Item 3">]
# Then you can get a list of models in the desired order using `sort_by` and `index`
items.sort_by { |item| indexed_ids[item.id] }
#=> [#<struct Model id=3, name="Item 3">, #<struct Model id=2, name="Item 2">, #<struct Model id=1, name="Item 1">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment