R
Raymond O'Connor
Using sort with a multiline block doesn't seem to work as expected.
Single line blocks work fine:
[3, 7, 4, 1, 8, 2, 8, 9].sort { |a, b| a <=> b }
#returns [1, 2, 3, 4, 7, 8, 8, 9]
[3, 7, 4, 1, 8, 2, 8, 9].sort { |a, b| b <=> a }
#returns [9, 8, 8, 7, 4, 3, 2, 1]
Multiline blocks ALWAYS sort in ascending order for some reason:
[3, 7, 4, 1, 8, 2, 8, 9].sort do |a, b|
a <=> b
end
#returns [1, 2, 3, 4, 7, 8, 8, 9]
[3, 7, 4, 1, 8, 2, 8, 9].sort do |a, b|
b <=> a
end
#returns [1, 2, 3, 4, 7, 8, 8, 9]
In fact even when I code the comparison by hand, it's still always
ascending:
[3, 7, 4, 1, 8, 2, 8, 9].sort do |a, b|
if a < b
1
elsif a > b
-1
else
0
end
end
#returns [1, 2, 3, 4, 7, 8, 8, 9]
Does anyone know what's going wrong with this?
Thanks
Single line blocks work fine:
[3, 7, 4, 1, 8, 2, 8, 9].sort { |a, b| a <=> b }
#returns [1, 2, 3, 4, 7, 8, 8, 9]
[3, 7, 4, 1, 8, 2, 8, 9].sort { |a, b| b <=> a }
#returns [9, 8, 8, 7, 4, 3, 2, 1]
Multiline blocks ALWAYS sort in ascending order for some reason:
[3, 7, 4, 1, 8, 2, 8, 9].sort do |a, b|
a <=> b
end
#returns [1, 2, 3, 4, 7, 8, 8, 9]
[3, 7, 4, 1, 8, 2, 8, 9].sort do |a, b|
b <=> a
end
#returns [1, 2, 3, 4, 7, 8, 8, 9]
In fact even when I code the comparison by hand, it's still always
ascending:
[3, 7, 4, 1, 8, 2, 8, 9].sort do |a, b|
if a < b
1
elsif a > b
-1
else
0
end
end
#returns [1, 2, 3, 4, 7, 8, 8, 9]
Does anyone know what's going wrong with this?
Thanks