Afficher un message
Vieux 06/11/2007, 22h42   #1
Raymond O'Connor
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Sort and a multiline block

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
--
Posted via http://www.ruby-forum.com/.

  Réponse avec citation
 
Page generated in 0,04880 seconds with 9 queries