PDA

View Full Version : Arranging an Array


sheefo
July 30th, 2006, 09:48 AM
I need to arrange an array or hash in order of there objects attributes. Like this:

$LAYERS = Array.new
class Bitmap
attr_accessor :layer
def initialize
$LAYERS << self
end
end

bitmap = Bitmap.new
bitmap.layer = 10

bitmap2 = Bitmap.new
bitmap2.layer = 999

def update
# CODE for Arranging an Array
end


'bitmap2' should be before 'bitmap' in the array and if you add a new one the code for re-arranging the array initializes again.

motobass
July 30th, 2006, 04:47 PM
Add this to your Bitmap class:

def <=>(other)
other.layer <=> self.layer
end

Then the update method is simply,

$LAYERS.sort

If you call the sort method before they are assigned a layer, things will blow up.

sheefo
July 30th, 2006, 05:22 PM
Wow, thanks! It work perfectly :)

I am using it for my game engine that uses Ruby-SDL to render the images to the screen, also for playing audio. I am programming the entire engine with all the commands to manipulate the images and stuff.

You have just help me implement bitmap layers. Thanks again :)

motobass
July 31st, 2006, 12:20 AM
You're welcome. I got that straight out of the Pickaxe book, 2nd ed., by the way. It's called the spaceship operator, appropriately enough.

sheefo
July 31st, 2006, 05:17 AM
Sound like a useful source, I might check it out. I've never actually bought a Ruby book I just use the free "Pragmatic Programmer's Guide" that comes with Ruby, and the website http://ruby-doc.org/. Non of them actually tell you tips like Re-arranging arrays ;)

And thanks again :)