【问题标题】:Why does "include" behave differently in the global context than it does in a class?为什么“包含”在全局上下文中的行为与在类中的行为不同?
【发布时间】:2013-10-18 18:32:20
【问题描述】:

在全局上下文(main)中,当你包含一个模块时,你可以直接从全局上下文中使用它的方法。在一个类中,包括模块定义了不能从调用 include 的同一上下文中调用的实例方法。这是为什么呢?

例子:

module Foo
  def hello
    puts "Hello, world!"
  end
end

# In a class:
class Bar
  include Foo
  hello # Hello is an instance method so it won't work here.
end

# In main
include Foo
hello # Works fine. Why?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    主要

    包括 Foo

    你好#工作正常。为什么?

    What is the Ruby Top-Level? 一个关于这个概念的好博客,你必须先通读一遍。

    因为在顶层你正在调用顶层对象main上的实例方法#hello,这是Object类的一个实例。在顶层你正在做include Foo意味着你正在包含模块在Object 类中。这就是为什么模块Foo 的实例方法#hello 成为类object 的实例方法。

    module Foo
      def hello
        puts "Hello, world!"
      end
    end
    Object.include?(Foo) # => false
    include Foo
    Object.include?(Foo) # => true
    self # => main
    self.class # => Object
    self.instance_of? Object # => true
    hello # => Hello, world!
    

    如果您将方法调用为hello,则在顶层,但ruby 在内部以self.hello 执行。还有selfmain,我之前解释过。

    【讨论】:

    • "因为在顶层你是在顶层对象main上调用实例方法#hello,它是Object类的一个实例。"坚持,稍等。如果mainObject 类的一个实例,那么include 怎么会在顶层工作而Object.new.send(:instance_eval) do include Foo; end 不能呢? (它为include 抛出一个NoMethodError。)
    • 我的意思是,include 没有在 Object 上定义:Object.new.respond_to? :include #=> false。那么为什么在main上定义呢?
    • @Ajedi32 请仔细阅读What is the Ruby Top-Level?
    • @Ajedi32 你能来吗? chat.stackoverflow.com/rooms/38656/…
    • 好的,所以main 不仅仅是Object 的一个实例,它还具有所有其他特殊行为。这回答了我的问题,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 2021-01-29
    相关资源
    最近更新 更多