Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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">]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement