On Mon, Jul 12, 2004 at 07:33:51AM +0900, Sam Stephenson wrote: > There's a few trivial but useful "extensions" to Ruby's standard > library that I find myself using in most of my projects. I'll share a > couple, and I'd really love to see what you're using, too. > > Array folding is a functional idiom in which each item is evaluated in > some way and its result accumulated, returning the final value of the > accumulator. It's simple in Ruby: > > | class Array > | def foldl(accum, &block) > | each {|value| accum = yield(accum, value)} > | return accum > | end > | def foldr(accum, &block) > | reverse.foldl(accum, &block) > | end > | alias fold :foldl > | end > > The canonical example is summing values: > > | r = (1..100).to_a > | p r.foldl(0) {|a,v| a += v} > => 5050 > | p r.foldr(5050) {|a,v| a -= v} > => 0 > > A more interesting and useful application involves boolean logic. For > example, the following snippet ensures all arguments passed to > FooSet#new are of type Foo: > > | class Foo; end > | class FooSet > | def initialize(*values) > | raise TypeError unless > | values.fold(true) {|a,v| a and v.is_a? Foo} > | # ... > | end > | end There's an easier way to do it: values.all? {|v| v.is_a? Foo} Regards, Michael