Hi –
I see that Enumerable.partition has been added somewhere between 1.6.7
and 1.7.3. It’s implemention is equivilent to
module Enumerable
def partition
result = [[], [[]]
each do |value|
result[yield(value) ? 0 : 1].push(value)
end
result
end
end
e.g. [0, 1, 2, 3].new_parition { |x| x > 1 }
gives [[2, 3], [0, 1]]
Please (pretty please) can this be changed to the much more powerful:
module Enumerable
def new_partition(default = nil)
result = Hash.new(default)
each do |value|
key = yield(value)
if result.has_key?(key)
result[key].push(value)
else
result[key] = [value]
end
end
result
end
end
e.g. [0, 1, 2, 3].new_partition { |x| x > 1 }
gives {false=>[0, 1], true=>[2, 3]}
Hopefully this won’t break too much code in 1.7.3. It’s very useful:
[-2, -1, 0, 1, 2].new_partition { |x| x <=> 0 }
=> {0=>[0], 1=>[1, 2], -1=>[-2, -1]}
The ability to override the hash default is helpful:
a = [0, 1, 2]
h = a.partition([]) { |x| x <=> 0 }
=> {0=>[0], 1=>[1, 2]}
puts(“there are #{h[-1].size} negative numbers in a”)
Thanks,
Tom