M
Martin DeMello
class Enumerable
def build(seed)
each {|i|
seed.add(yield i)
}
end
end
and
Array#build == Array#<<
Hash#build(k,v) == Hash#[]
etc
So you could say [1,2,3].build({}) {|i| [i, 1]} for the question that
prompted the to_hash thread, but also, in general, you can collect into
non-array structures (binary trees, e.g.) as long as they implement a
suitable #add method.
(Of course, you can do ary.inject(seed) {|i| seed.add(f(i)); seed} right
now but a #build method makes the common case pretty.)
martin
def build(seed)
each {|i|
seed.add(yield i)
}
end
end
and
Array#build == Array#<<
Hash#build(k,v) == Hash#[]
etc
So you could say [1,2,3].build({}) {|i| [i, 1]} for the question that
prompted the to_hash thread, but also, in general, you can collect into
non-array structures (binary trees, e.g.) as long as they implement a
suitable #add method.
(Of course, you can do ary.inject(seed) {|i| seed.add(f(i)); seed} right
now but a #build method makes the common case pretty.)
martin