Suppose we want to sort a collection of accounts by their account balance. We could put them in ascending order like this:
@accounts.sort {|x,y| x.balance <=> y.balance}
Or descending order like this:
@accounts.sort {|x,y| y.balance <=> x.balance}
To me this isn’t very readable. How about this as an alternative:
@accounts.sort_by_ascending(:balance)
# or
@accounts.sort_by_descending(:balance)
The implementation is pretty simple, first create the methods:
module ReadableSortBy
def sort_by_ascending(method)
sort {|x, y| x.send(method) <=> y.send(method)}
end
def sort_by_descending(method)
sort {|x, y| y.send(method) <=> x.send(method)}
end
end
Then include them in Array:
class Array
include ReadableSortBy
end
You could also make sort_by_ascending! and sort_by_descending! methods that modify the collection itself. Do this by replacing sort with sort! in both cases.