Hello --

On Fri, 8 Nov 2002, Booth, Peter wrote:

> I'm wondering if there is a more idiomatic way to do the following?
> Can Array.collect be used to extract a subset of an array?
>
> Peter
>
> Can
>
> class ProcessInfo < Array
>
> 	def findByRealm(realm)
> 		result = ProcessInfo.new
> 		each { |process|
> 			if process['realm'] == realm
> 		  		result << process
> 		  	end
> 		 }
> 		 return result
> 	end
>
> end

[untested code follows]

You could do something like:

  class ProcessInfo < Array
    def find_by_realm(realm)
      find_all {|e| e['realm'] == realm}
    end
  end

This will return an Array, not a ProcessInfo object.  You could however
change it to:

  class ProcessInfo < Array
    def find_by_realm(realm)
      self.class.new.replace(find_all {|e| e['realm'] == realm})
    end
  end

which creates a new object of the same class as 'self' (which might be
useful if you inherit from ProcessInfo) and populates it with the
results of the filter (find_all) operation.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav