Except Methods for Arrays in Ruby

by Castwide on 3-3-2008 • Tags: code, ruby10 comments

While working on the next generation of an adventure game engine I wrote, I noticed a piece of code that I frequently needed to repeat.  Every object in the game, including the player's character, inherits from a common Entity class.  There are several functions that need to iterate through all the entities in the player's current location except the player.  Each entity has a parent property that returns its container, so the code would look something like this:


player.parent.children.each { |child|
if child != player
# Do something
end
}

I wanted an easier way to do the same thing, so I extended the Array class with two new methods: except and except! The except method returns a copy of the array excluding the objects passed as arguments.  The except! method modifies the array in place, deleting the objects in the arguments.  In the game's scripts, the above code would now look like this:


player.parent.children.except(player).each { |child|
# Do something
}

The except methods can exclude any number of objects.


player.parent.children.except(player, foo, bar, baz).each { |child|
# Do something
}

The code to add the methods to the Array class is as follows:


class Array
def except(*exceptions)
result = self.clone
result.delete_if { |i|
exceptions.include?(i)
}
result
end
def except!(*exceptions)
self.delete_if { |i|
exceptions.include?(i)
}
self
end
end

The more I work with Ruby, the more I like it.

Comments

homeowners insurance in florida =-) home insurance gnzmgf
car insurance quotes 2397 life insurance 16393
life insurance for seniors >:P auto insurance rates 3286
no exam life insurance igvzlf health insurance rates 5629
health insurance quotes >:((( universal life insurance 373244
cheap generic cialis >:-D ultram :(
individual health insurance plans uszehe life insurance rate 3397
ultram 07223 ultram tramadol mailorder ktiyms
ultram :]] order viagra online :]]]
levitra =-] cialis dmpzjw

Add Comment

More Articles