Submitted by NickJohnson (Sun Apr 11 16:04:40 UTC 2004)
For example, suppose I want to construct the Koch curve (see I would start by creating a class for a line segment in R^2 space. Then, with the current implementation of Array, I would create an array containing one such line segment, and call:
setOfLineSegments=[LineSegment.new(...)] setOfLineSegments.collect! do |ls|
[
# each line segment is
# replaced by 4
LineSegment.new(...)
LineSegment.new(...)
LineSegment.new(...)
LineSegment.new(...)
]
end setOfLineSegments.flatten!
Such iterative approximation of an infinite and recursively defined set is common. Such code would be more readable with collect_flatten and collect_flatten! methods of array.
These methods could be implemented as either a call to collect and then to flatten, or as a call to collect and concat (either would be ok with me).
I feel that the collect and flatten pair makes more intuitive sense, though the collect and concat pair may be faster.
class Array
def collect_flatten(&block)
r = collect(&block)
r.flatten
end
def collect_flatten!(&block)
collect!(&block)
flatten!
end
end
Comments | Current voting | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
RCRchive copyright © David Alan Black, 2003-2005.
Powered by .
Have you considered inject, like this?
-- Simon Strandgaard