【问题标题】:Generic methods/Default methods in Ruby, when some method is not definedRuby 中的通用方法/默认方法,当某些方法未定义时
【发布时间】:2012-05-23 18:15:01
【问题描述】:

我想做点什么,但不确定是否可行。如果调用了某些方法但未定义,我想使用“通用方法”或“默认方法”。这是一个简单的例子,所以你可以理解我的观点:

这是课程:

class XYZ

    def a
        #...
    end

    def b
        #...
    end
end

XYZ 类的实例:

n = XYZ.new
n.a
n.b
n.c

如您所见,我调用了未定义的方法“c”,它会抛出错误。我可以在类 XYZ 中做某事,因此当有人调用未定义的方法时,获取该方法的名称并根据该方法的名称做某事?而且,这在其他语言中是否可能(不制作编译器)?如果这是可能的,它怎么称呼(理论上)?

【问题讨论】:

    标签: ruby oop metaprogramming


    【解决方案1】:

    使用method_missing:

    class XYZ
      def a; end
      def b; end
    
      def method_missing(name, *args)
        "Called #{name} with args: #{args}"
      end
    end
    
    XYZ.new.c #=> "Called c"
    

    您还应该定义 respond_to_missing? 以使 respond_to? 在 1.9.2+ 中更好地工作。你应该read more about respond_to?/respond_to_missing? when using method_missing

    顺便说一句,这将被视为元编程。这在编译语言中通常是不可能的,因为它们调用函数的方式。

    【讨论】:

      【解决方案2】:

      它被称为method_missing。 当您调用未在对象上定义的方法时,ruby 会将调用重定向到 method_missing 方法,这会为您引发错误。

      你可以这样做:

      class XYZ
        def method_missing(method, *args, &blck)
          puts "called #{method} with arguments #{args.join(',')}"
        end
      end
      

      现在您将得到控制台的输出,而不是错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-25
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-13
        相关资源
        最近更新 更多