Another Ruby Except Method

by Castwide on 3-7-2008 • Tags: code, ruby8 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

Comments

car insurance 048 auto insurance 8-D
home insurance dlmlzi auto insurance quotes jhybwz
life insurance :-( healthinsurance 5630
home insurance lsphsb auto insurance quotes =-))
home insurance %-[ new jersey car insurance qxdzcj
online car insurance eunpx health insurance quotes 8-P
buy namebrand tramadol 762316 cialis xjeda
cialis cipv buy ms site tramadol jjzgd

Add Comment

More Articles