Ruby – How to pass arguments to define_method

metaprogrammingruby

I would like to pass an argument(s) to a method being defined using define_method, how would I do that?

Best Solution

The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So:

define_method(:say_hi) { |other| puts "Hi, " + other }