Another Ruby Except Method

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

In a previous article I documented an "except" method for arrays in Ruby.  This method returns a copy of the array excluding elements which equal objects passed in the argument.  An example of how it's used:


newArray = myArray.except(foo, bar)

newArray will contain all of myArray's elements except those which equal foo and bar.

In many cases, the program may only need to execute a function on each of the array's members, so creating a new array is overkill.  One solution is an each_except method:

myArray.each_except(foo, bar) { |child|
puts "This element: #{child}"
}

The above code will execute the procedure for each element in the array that is not equal to foo or bar.

Following is the code to extend the Array class with except, except!, and each_except methods:


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
def each_except(*exceptions)
self.each { |i|
if exceptions.include?(i) == false
yield(i)
end
}
end
end

There are no comments posted to this news item.

Add Comment

More Articles