1

I have a constant

TYPES = %w(car truck)

I want to define custom assignment methods dynalically

TYPES.each do |type|
  define_method "#{type}s=(objects)" do

But it doesn't work, when I call

myobject.cars=objects

I am getting an error method doesn't exists although I can trace it

puts myobject.methods

does have a method

cars=(objects)
Petran
  • 7,677
  • 22
  • 65
  • 104

3 Answers3

3

define_method expects method name, not signature.

define_method "#{type}s=" do |objects|
  puts objects
end
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
1

You have to write something like this to make it work:

define_method "#{type}s=" do |objects|
Szymon
  • 242
  • 1
  • 9
0

define_method(symbol) { block } → symbol The actual method is in the block, and the params of block is the params of the actual method. Here is the description from Ruby docs. Defines an instance method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.)

Daniel
  • 869
  • 2
  • 7
  • 19