0

I just wondered about some metaprogramming.

Actually I need to create a method within a method, or just create a method in the root of a class by a block. example:

["method_a", "method_b"].each do |m|
  Marshal.generate_a_method_called(m)
end

Does somebody know how this is possible? And where to place what the method does? I need one argument for my method.

Yours,

Joern.

2 Answers 2

4

You could use define_method:

[:method_a, :method_b].each do |m|
  define_method(m) do
    # your method stuff
  end
end
Sign up to request clarification or add additional context in comments.

Comments

1

I don't understand your example. Are you generating the source for the method as well?

So I will start with an example from the book Perrotta: Metaprogramming Ruby

class MyClass
  define_method :my_method do |my_arg|
    my_arg * 3
  end
end

obj = MyClass.new
obj.my_method(2) # => 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.