Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. # Given #1: a list of ids in a specific order you want to preserve
  2. ordered_ids = (1..3).to_a.reverse
  3. #=> [3, 2, 1]
  4. indexed_ids = ordered_ids.each_with_index.to_h
  5. #=> {3=>0, 2=>1, 1=>2}
  6.  
  7. # Given #2: a collection of items with the same ids as in the list above, but in no particular order
  8. # Example: `Model.where(…)` in rails
  9. Model = Struct.new(:id, :name)
  10. items = (1..3).map { |id| Model.new(id, "Item #{id}") }
  11. #=> [#<struct Model id=1, name="Item 1">, #<struct Model id=2, name="Item 2">, #<struct Model id=3, name="Item 3">]
  12.  
  13. # Then you can get a list of models in the desired order using `sort_by` and `index`
  14. items.sort_by { |item| indexed_ids[item.id] }
  15. #=> [#<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