Except Methods for Arrays in Ruby
by Castwide on 3-3-2008 Tags: code, ruby 0 commentsWhile 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.