On 2/3/06, Robert Klemme <bob.news / gmx.net> wrote:> > I think that inject_with_state could be made fully backwards> > compatible to inject, it would be nice if inject could be changed to> > support this. What do you think?>> You don't need to redefine Enumerable#inject for this.>> >> def count_streams(enum)> >> enum.inject([[],nil]) {|(a, last),e|
Thanks, I was not aware that parameters can be grouped like that.
But I think that an Enumerable#inject with additional parameters wouldalso be useful for many other things, like removing duplicates:
def remove_duplicates1(enum) enum.inject([[], nil]) {|(arr, last),elem| arr << elem unless elem== last; [arr, elem] }[0] end def remove_duplicates2(enum) enum.inject([], nil) {|(arr, elem, last| arr << elem unless elem== last; [arr, elem] } end
The second one seems looks a lot cleaner.
> Also, I'm not sure it's a good idea to put this method in Enumerable. Is> it really general enough?
No, it probably is not. This was just a for small experiment (*), iwould not put this into a library.(However, it seems to be preferred to put methods into the class"where they belong" in Ruby instead of using helper classes)
Thank you,Levin
(*) <http://www.rexswain.com/benford.html>"...It showed, he said, that the overwhelming odds are that at somepoint in a series of 200 tosses, either heads or tails will come upsix or more times in a row."
(0..10_000).select { (0..200).map { rand 2 }.inject([[],nil]) {|(a,last),e| if e==last then a[-1]+=1 else a << 1 end [a,e] }[0].partition { |e| e >= 6 }.first.empty? }.length / 10_000.0 #=> 0.0349
"overwhelming odds" --> 97%