From: Joel VanderWerf Date: 2003-05-11T09:11:47+09:00 Subject: [RCR?] Enumerable#each with arguments I've been using REXML lately and wishing I could do something like this: elt = ... # get a REXML::Element somehow elt_parts = elt.elements.collect('part') # XPath query The #collect call fails because it requires 0 arguments. But each can be called with an argument, so the following does what I want: elt_parts = [] elt.elements.each('part') { |x| elt_parts << x } Or I could use #select, but then it's extra work to get the XPath functionality. This leads to a general suggestion: instance methods in Enumerable should pass on their arguments to each. To be more specific, here's an example that doesn't work now: class Foo include Enumerable def initialize; @stuff = [1,2,3]; end def each(n=nil) if n @stuff.each {|x| yield x if x < n} else @stuff.each {|x| yield x} end end end foo = Foo.new foo.each(2) {|x| p x} # ==> 1 #p foo.collect(2) # ==> should be [1], but wrong number of args At this point #collect can't be called with arguments. But it's easy to fix: class Foo def collect(*args) rslt = [] each(*args) {|x| rslt << x} rslt end end p foo.collect(2) # ==> [1] I could always redefine collect and friends in Enumerable, but why not add this behavior in enum.c? Maybe there's a performance cost...?