I’ve been trying to use sort for an array and I seem to be missing
something. Here’s my code and results.
#!/usr/local/bin/ruby
arr = [“a”, “G”, “b”, “f”]
arr.sort
print "Sort #1\n"
for atom in arr
print atom, "\n"
end
arr.sort { |x, y| y <=> x}
print "\n\nSort #2\n"
for atom in arr
print atom, "\n"
end
[localhost:~/src/ruby] steve% ./dirsort.rb
Sort #1
a
G
b
f
Sort #2
a
G
b
f
What I’m guessing is that the item I think is an array is not actually
an array or the comparison is working the way I think it is supposed to.
If anyone can let me know what I’m doing wrong, I’d appreciate it.
Thanks,
Steve
“Steve Peters” stmpeters@eSaPrAtMhlink.net wrote in message
news:oQRh9.1471
If anyone can let me know what I’m doing wrong, I’d appreciate it.
You are forgetting that Array#sort is not destructive.
Try this:
arr = [“a”, “G”, “b”, “f”]
bArr = arr.sort
print “Sort #1\n”
for atom in bArr
print atom, “\n”
end
cArr = arr.sort { |x, y| y <=> x}
print “\n\nSort #2\n”
for atom in cArr
print atom, “\n”
end
Does that work ?
– shanko
arr.sort doesn’t change the order of arr but returns a new array with
arr’s elements which happens to be sorted. If you want to sort arr
itself you have to use arr.sort! instead of arr.sort. You could also
use the return value of arr.sort:
for atom in arr.sort
print atom, “\n”
end
···
Am 2002-09-18 12:09:04 +0900 schrieb Steve Peters:
If anyone can let me know what I’m doing wrong, I’d appreciate it.
–
Conservatives are not necessarily stupid, but most stupid people are
conservatives.
– John Stuart Mill