代码之家  ›  专栏  ›  技术社区  ›  Jorge Israel Peña

Ruby动态方法帮助

  •  1
  • Jorge Israel Peña  · 技术社区  · 15 年前

    我需要一些帮助来定义动态方法。

    基本上,我有许多类驻留在一个模块中。我需要根据传入的字符串列表在每个类中生成一个方法列表,该列表是特定于每个类的(即不同的类具有不同的字符串列表)。方法的主体应类似于:

    client.call(the_string, @an_instance_variable)
    

    所以基本上我想创建一个方法,我可以在这些类中的每个类中使用,这些类驻留在同一个模块中,以便根据传递的字符串数组动态生成一组方法。

    类似:

    register_methods @@string_array
    

    所以说“name”是数组中的一个字符串,那么它将生成一个这样的方法:

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

    我希望这是有道理的。我在做了好几个小时的各种各样的事情之后,感到很头疼,我真的很感激你的意见。谢谢!

    2 回复  |  直到 15 年前
        1
  •  4
  •   Matt Briggs    15 年前

    没有可用的IRB,但这应该有效

    def register_methods strings
      strings.each do |s|
        define_method s.to_sym do
          client.call("name", @an_instance_variable)
        end
      end
    end
    
        2
  •  0
  •   DanneManne    15 年前

    我不知道您打算如何使用@an_instance_变量,但您也可以定义采用如下参数的方法:

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

    因此,如果您发送register_methods(“name”,“age”),您将有两种新的方法,如下所示:

    def name(arg)
      client.call("name", arg)
    end
    
    def age(arg)
      client.call("age", arg)
    end
    
    推荐文章