代码之家  ›  专栏  ›  技术社区  ›  horseyguy

ruby顶层定义的方法在哪里?

  •  7
  • horseyguy  · 技术社区  · 16 年前

    在顶层,方法定义应该在 Object ,测试似乎证明了这一点:

    def hello; "hello world"; end
    
    Object.private_instance_methods.include?(:hello) #=> true
    Object.new.send(:hello) #=> "hello world"
    

    但是,以下内容也适用于顶层( self.meta 是的特征类 main

    self.meta.private_instance_methods(false).include?(:hello) #=> true
    

    看来 hello 该方法同时定义了主系统的特征类和子系统的特征类 . 发生什么事?请注意 false 参数到 private_instance_methods 从方法列表中排除超类方法。

    1 回复  |  直到 11 年前
        1
  •  8
  •   Pesto    16 年前

    首先,这种行为和潜在的推理一直存在;这对1.9来说并不是什么新鲜事。它发生的技术原因是 main

    有魔力吗?因为Ruby的设计师松本幸弘认为 makes the language better 要具有此行为,请执行以下操作:

    那么,为什么顶级方法不能在这个对象上创建单例方法呢, 它本身 (并因此进入所有其他类,即名称空间污染比 通常是有意的)。这仍然允许顶级方法调用其他方法 顶级方法。如果顶级对象是由 一些 常量,那么这些方法可以从任何地方调用 具有

    你真的想打字吗 到处都是“Main.print”?

    在进一步的讨论中,他解释说,这是因为他觉得“假设是自然的”

    hello 作为私有实例方法。问题是没有一个顶级函数实际添加到 ,但直接向 Object instance_methods 函数族始终表现为本征类仍然是原始类。也就是说,在类中定义的方法被视为直接在特征类中定义。例如:

    class Object
      private
      def foo
        "foo"
      end
    end
    
    self.send :foo  # => "foo"
    Object.private_instance_methods(false).include? :foo  # => true
    self.meta.private_instance_methods(false).include? :foo  # => true
    
    class Bar
      private
      def bar
        "bar"
      end
    end
    
    bar = Bar.new
    bar.send :bar  # => "bar"
    Bar.private_instance_methods(false).include? :bar  # => true
    bar.meta.private_instance_methods(false).include? :bar  # => true
    

    主要的 不过,这是一个典型的特征类。将您的原始示例与此进行比较:

    def self.hello; "hello world"; end
    
    Object.instance_methods.include? :hello  # => false
    self.meta.instance_methods.include? :hello  # => true
    

    好的,但是如果我们真的想知道给定的函数是在本征类上定义的,而不是在原始类上定义的呢?

    def foo; "foo"; end  #Remember, this defines it in Object, not on main
    def self.bar; "bar"; end  #This is defined on main, not Object
    
    foo  # => "foo"
    bar  # => "bar"
    
    self.singleton_methods.include? :foo  # => false
    self.singleton_methods.include? :bar  # => true
    
    推荐文章