Last active
December 17, 2015 11:59
-
-
Save elado/5606443 to your computer and use it in GitHub Desktop.
Order / Limit an Array, like in SQL: array.order('score DESC, name').limit(3)
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
class Array | |
DESC_RX = /\s*desc$/i | |
ASC_DESC_RX = /\s*(?:asc|desc)$/i | |
def order(by) | |
by = by.split(',').map(&:strip) | |
sort do |a, b| | |
by_is_desc = by.map { |col| col =~ DESC_RX } | |
by_cols = by.map { |col| col.sub(ASC_DESC_RX, "") } | |
by_values_a = by_cols.map { |col| a.send(col) } | |
by_values_b = by_cols.map { |col| b.send(col) } | |
by_is_desc.each.with_index do |is_desc, i| | |
next unless is_desc | |
by_values_a[i], by_values_b[i] = by_values_b[i], by_values_a[i] | |
end | |
by_values_a <=> by_values_b | |
end | |
end | |
def limit(*args) | |
if args.length > 1 | |
slice(args[0], args[1]) | |
else | |
first(args[0]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment