开发者

Ruby Help with Dynamic Methods

I need some help with defining a dynamic method.

Basically, I have many classes that reside within one module. I need to generate a list of methods within each class based on a passed in list of strings, which is specific to each class (i.e. different classes have different list of strings). The body of the method should be something like:

client.call(the_string, @an_instance_variable)

So basically I want to create a method that I can use in each of these classes that reside within the same module, in order to dynamically generate a bunch of methods based on the array of str开发者_StackOverflow中文版ings that was passed.

Something like:

register_methods @@string_array

So say "name" was a string in the array, then it would generate a method as such:

def name
  client.call("name", @an_instance_variable)
end

I hope that makes sense. I'm stumped after trying all sorts of things for hours, and would really appreciate any input. Thanks!


don't have an irb available, but this should work

def register_methods strings
  strings.each do |s|
    define_method s.to_sym do
      client.call("name", @an_instance_variable)
    end
  end
end


I don't know how you intend do use the @an_instance_variable, but you can also define methods that takes arguments like this:

def register_methods *methods
  methods.each do |method|
    define_method method do |arg|
      client.call(method, arg)
    end
  end
end

So if you send register_methods("name", "age") you would have two new methods looking like this:

def name(arg)
  client.call("name", arg)
end

def age(arg)
  client.call("age", arg)
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜