相关疑难解决方法(0)

为什么模块的单例方法在混合的下游特征类中不可见?

我理解常规方法查找路径即class, superclass/module, all the way up to BasicObject.我认为对于单链版本的链也是如此,但是当您在元链中混合模块时似乎并非如此.我很感激,如果有人能解释为什么在下面的示例中,当我将此模块包含在Vehicle的本征类中时,调用Automobile模块的banner方法而不是单例版本.

module Automobile
  def banner
    "I am a regular method of Automobile"
  end

  class << self
    def banner
      "I am a singleton method of Automobile"
    end
  end
end

class Vehicle 
  def banner
    "I am an instance method of Vehicle"
  end

  class << self
    include Automobile
    def banner
      puts "I am a singleton method of Vehicle"
      super
    end
  end
end

class Car < Vehicle
  def banner
    "I am …
Run Code Online (Sandbox Code Playgroud)

ruby inheritance mixins eigenclass

7
推荐指数
1
解决办法
1012
查看次数

为什么我可以使用诸如puts之类的内核单例方法?

在Ruby中,该方法putsKernel模块的单例方法。

通常,当一个模块是另一个模块的included或extended时,该模块(而不是其单例类)将被添加到继承树中。这有效地使模块的实例方法可用于该模块或其单例类(分别用于includeextend)...但是混合模块的单例方法仍然不可访问,因为模块的单例类不是曾经添加到继承树中。

那为什么要使用puts(和其他内核单例方法)?

Kernel.singleton_methods(false)

# => [:caller_locations, :local_variables, :require, :require_relative, :autoload, :sprintf, :format, :Integer, :Float, :String, :Array, :Hash, :test, :warn, :autoload?, :fork, :binding, :exit, :raise, :fail, :global_variables, :__method__, :__callee__, :__dir__, :URI, :eval, :iterator?, :block_given?, :catch, :throw, :loop, :gets, :sleep, :proc, :lambda, :trace_var, :untrace_var, :at_exit, :load, :Rational, :select, :Complex, :syscall, :open, :printf, :print, :putc, :puts, :readline, :readlines, :`, :p, :system, :spawn, :exec, :exit!, …
Run Code Online (Sandbox Code Playgroud)

ruby eigenclass

6
推荐指数
1
解决办法
86
查看次数

标签 统计

eigenclass ×2

ruby ×2

inheritance ×1

mixins ×1