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…

I got this far

def sigma(floor, to_do, cap)

end
puts sigma(4, ^2, 20)

I will fiddle with your suggestions and continue with my sigma

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…

sum = (m…n).inject(0){|s,x| s + f[x]}
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.

What’s top post? (sorry, I’m new to google groups --I put my reply at
the bottom if this is what you meant )

I’ll read through your example now but figured what I worked on in the
interim was worth posting…

#works
def test(a, to_do, b)
return a.send(to_do, b)
end
puts test(2, :**, 3)

#does not work when trying to send an entire mathematical expresion as
a param
def sigma(floor, to_do, cap)
x = 0
floor.upto(cap) {|i|
x += i.send(to_do)
}
return x
end
puts sigma(4, :**2, 20)

#does not work… but another example of what I would expect

}
return x
end
puts sigma(4, lambda{|x| x ** 2}, 20)

Thanks a million!

Basically if you think this further through, what you are trying to do
is already part of Ruby’s standard lib. The method is #inject. I think
I used it in one of my postings. Your piece above becomes

puts (4…20).inject(0) {|s,x| s + x ** 2}

or, to more directly translate using #upto

require ‘enumerator’
puts 4.to_enum(:upto, 20).inject(0) {|s,x| s + x ** 2}

#does not work when trying to send an entire mathematical expresion as
a param
def sigma(floor, to_do, cap)
x = 0
floor.upto(cap) {|i| #x += i.send(to_do)
x += to_do[i]
}
return x
end
puts sigma(4, lambda{|x| x ** 2}, 20)

Thanks a million!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.