Given an array like
x = [1, 3, 5, -1, -3, -5]
If we use the command
x.sort {|i| i}
We are given
x = [-1, -3, -5, 1, 3, 5]
Is there any way, given our array, to have it return it in proper ascending/descending order with negatives? E.g.
x = [-5, -3, -1, 1, 3, 5] or [5, 3, 1, -1, -3, -5]
EDIT:
It seems like x.sort would solve this problem, but if there was a more sophisticated problem in which I want to sort from my array based on values given in a hash e.g.
x = [{:i=>1}, {:i=>2}, {:i=>3}, {:i=>4}, {:i=>5}]
y = {3=>10, 4=>-1, 2=>-2, 5=>-3, 1=>-4}
I want to be able to sort x based on the values in y so that my result is
x = [{:i=>3}, {:i=>4}, {:i=>2}, {:i=>5}, {:i=>1}]
Your example yields unexpected results because of the return value expected by the
Array#sortmethod. Basically, when you return just the first argument (when two are expected), the interpreter only looks at the sign (-/0/+) of the element and uses that for ordering. So depending on the underlying sort algorithm, when it yields pairs from the array to your block it’s only looking at the sign of the first element, so something like:[Edit] Per your updated question, try using the following sort comparator block:
Which reads – sort the array
xin place by comparing each element pair,aandb, by looking up their:iattribute in the hashyand comparing those values in descending order.