Last active
February 23, 2018 19:02
-
-
Save IgnusG/adc652645a5e6ff486a228fed69d1ec9 to your computer and use it in GitHub Desktop.
Orders one array according to another array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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