Skip to content

Instantly share code, notes, and snippets.

@IgnusG
Last active February 23, 2018 19:02
Show Gist options
  • Save IgnusG/adc652645a5e6ff486a228fed69d1ec9 to your computer and use it in GitHub Desktop.
Save IgnusG/adc652645a5e6ff486a228fed69d1ec9 to your computer and use it in GitHub Desktop.
Orders one array according to another array
objects = []
order = %w(first second)
objects
.group_by(&:order_by_this) # Create grouping according to field
.each { |_, h| h.sort_by!(&:sort_each_by_this).reverse! } # Each hash sorted individually
.values_at(*order) # Sorting according to order
.compact # Reject empty hash keys (no elements for order item)
.flatten(1) # Remove hash table
.concat(objects.reject { |o| order.include? o.order_by_this }) # Append all unidentified at the end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment