I would like to send a function as a parameter to a Ruby class and save both the function and its execution, but I haven't figured out how to do it.
So far I have tried this:
def a(x,y)
return x+y
end
class miClase
def initialize(funcion, param1, param2)
@fun=funcion
@res=funcion.call(param1, param2)
end
end
miClase=miClase.new(method(:a),4,3)
puts(miClase.res)
puts(miClase.fun(2,2))
and i get the following error
main.rb:5: class/module name must be CONSTANT
Output I would expect
7
4
Update
Using your own code, you could add the method
fun
to be able to execute the saved method(function) again with the new parameters; for instance:The error is because ruby classes and modules must be written with the first letter capitalized:
The behavior you are looking for seems a bit strange to me, however you could achieve it by using the method
send
(although you don't really pass any method and you wouldn't save the method as such, just its name) together with another method inside the class that calls the saved method with the new parameters; for instance:This code could use some cleaning up, but I prefer to show it like this for clarity. If you tell us more about why you're looking for this behavior, we might be able to help you find a better solution.
That's metaprogramming: