I know how to set class methods, but how do I set instance methods on the fly?

129 Views Asked by At
  • I asked a previous question on class methods, but I really want to understand how to do this for instance methods as well. Thanks! =)

The code below sets class methods for a given array:

class Testing

  V4_RELATIONSHIP_TYPES=[1=>2,3=>4]

  V4_RELATIONSHIP_TYPES.keys.each do |key|
    self.class.send(:define_method, "get_#{key}_type".downcase) do
      return GuidInfo.get_or_new(PARAMS, V4_RELATIONSHIP_TYPES[key])
    end
  end
end

#so i can call Testing.get_1_key()

The question is: how can I get the same set of methods for the instance?

2

There are 2 best solutions below

1
On BEST ANSWER
self.send(:method, value)
0
On
class Testing
  V4_RELATIONSHIP_TYPES = { 1 => 2, 3 => 4 }

  V4_RELATIONSHIP_TYPES.each do |key, value|
    define_method("get_#{key}_type".downcase) do
      return GuidInfo.get_or_new(PARAMS, value)
    end
  end
end

# Now you can call Testing.new.get_1_key