From: Robert Klemme Date: 2004-07-12T17:57:24+09:00 Subject: Re: Ruby quickies and useful idioms "Sam Stephenson" schrieb im Newsbeitrag news:11fb0551040711161466c5309f@mail.gmail.com... > On Mon, 12 Jul 2004 07:47:12 +0900, Gavin Sinclair > wrote: > > 'foldl' is, I believe, the same as Enumeration#inject. Try checking > > out the docs for that, but: > > > > (1..100).inject(0) { |acc,x| acc + x } > > Wow, I didn't know about Enumerable#inject. Semantically, it's not > quite the same as foldl: for instance, it doesn't make sense to foldl > (or foldr) a Hash, since you're not guaranteed any order. That's not true. Since + is commutative it doesn't matter in which order you add elements up. And there's a whole lot other algorithms that don't depend on the order in which they are processed. Even if you need an order you can do (stupid example): sorted_keys = hash.sort.inject([]) {|keys, (key, val)| print key, " -> ", val, "\n"; keys << key } > Practically > speaking, however, it's much nicer, since I can use it with Range. > > As an aside: It would be nice to have a subclass of Enumerable that > guarantees item order; Array, Range, et al could mix it in. Which order? Insertion order, natural order of the elements or an arbitrary order? Regards robert