** SPOILER **

Don’t read on if you first want to experiment yourself.

On 17.01.2007 17:48, Neutek wrote:

Robert, I was actually reading the summation wiki and they had a few

code examples in C++/Java… I thought I’d goof a bit and write

something out in ruby. Of course, I hit the roadblock when trying to

pass math operators(or methods rather) to a method…

What is the “summation wiki”? Are you referring to this page?

http://en.wikipedia.org/wiki/Sum

If yes, here are some more ways:

# plain values

sum = (m…n).inject(0){|s,x| s + x}

# with a function

f = lambda {|i| i * 2}

sum = (m…n).inject(0){|s,x| s + f[x]}

# in a method

def sum(m, n, f)

(m…n).inject(0){|s,x| s + f[x]}

end

s = sum( 1, 2, lambda {|x| x * 2} )

etc.

Advantage of using lambdas is that they are more flexible than method

names and can contain arbitrary calculations.

Kind regards

robert

PS: Please don’t top post.