Search code examples
ruby-on-railsrubyinstance-methodsdynamic-method

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


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


Solution

  • self.send(:method, value)