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])
开发者_如何学Goend
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?
self.send(:method, value)
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
精彩评论