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?

apaderno
  • 28,547
  • 16
  • 75
  • 90
meow
  • 27,476
  • 33
  • 116
  • 177

2 Answers2

4
self.send(:method, value)
Toby Hede
  • 36,755
  • 28
  • 133
  • 162
  • 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 – meow Aug 27 '10 at 02:51
2
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
  • 363,080
  • 75
  • 446
  • 653