views:

44

answers:

2
  • 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?

+4  A: 
self.send(:method, value)
Toby Hede
thanks a lot toby! sorry for naive question, did not know it was that simple, but should have guessed. I am still learning about all these dynamic methods, blocks, etc
ming yeow
+2  A: 
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
Jörg W Mittag