【问题标题】:Ruby: Defining methods dynamically based on variable valuesRuby:根据变量值动态定义方法
【发布时间】:2014-03-19 13:47:05
【问题描述】:

我想实现如下所示。根据数组参数定义方法名称并调用它们。

arr = ['alpha', 'beta', 'gamma'] arr.each { |角色| # 如果方法已经存在就不要定义新的 如果 !方法存在? “初始化_#{角色}” 定义“init_#{角色}” p "我是方法 init_#{role}" 结尾 } init_beta init_gamma

编辑: 如果这样的方法已经存在,不要定义新的方法。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    如下操作:

    arr = ['alpha', 'beta', 'gamma']
    
    arr.each do |role|
      # this code is defining all the methods at the top level. Thus call to 
      # `method_defined?` will check if any method named as the string argument 
      # is already defined in the top level already. If not, then define the method.
      unless self.class.private_method_defined?( "init_#{role}" )
        # this will define methods, if not exist as an instance methods on 
        # the top level.
        self.class.send(:define_method, "init_#{role}" ) do
          p "I am method init_#{role}"
        end
      end
    end
    
    init_beta # => "I am method init_beta"
    init_gamma # => "I am method init_gamma"
    

    查看private_method_defineddefine_method的文档。

    注意:我使用private_method_defined?,作为顶层,您将定义的所有实例方法(在默认可访问性级别中使用defdefine_method),变为private Object 的实例方法。现在根据您的需要,您还可以相应地检查protected_method_defined?public_method_defined?

    【讨论】:

    • 我收到错误“未定义的方法`method_defined?'对于主:对象(NoMethodError)”。 Ruby 版本是 'ruby 1.9.3p194(2012-04-20 修订版 35410)[x86_64-linux]'
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 2011-07-04
    • 2011-02-01
    • 1970-01-01
    • 2019-04-19
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多