On 17.01.2007 15:06, Neutek wrote:
> I'm trying to figure out how to pass methods such as:
> +, -, **, ^
> to a method and evaluate.
> 
> For example,
> 
> def test(a, b, to_do)
>    return a.send(to_do(b))
> end
> 
> 
> puts test(1, 2, "+") #should return 3
> puts test(3, 3, "^") #should return 0
> puts test(3, 3, "**") #should return 27
> 
> any help would be appreciated.

Several ways to do it

irb(main):001:0> def test(a,b,op) a.send(op,b) end
=> nil
irb(main):002:0> test 1,2,:"+"
=> 3
irb(main):003:0> def test(a,b,op) a.send(op.to_sym,b) end
=> nil
irb(main):004:0> test 1,2,"+"
=> 3
irb(main):005:0> def test(a,b,op) op[a,b] end
=> nil
irb(main):006:0> test 1,2,lambda {|x,y| x+y}
=> 3

The last sample shows the more functional approach.

What are you trying to achieve?

Kind regards

	robert