ruby-on-rails - (Ruby,Rails)模块和库中 SELF 的上下文......?

标签 ruby-on-rails ruby scope self

关于在模块或库中使用“SELF”的快速问题。基本上,“SELF”的范围/上下文是什么,因为它属于模块或库,如何正确使用它?有关我所说内容的示例,请查看随“restful_authentication”一起安装的“AuthenticatedSystem”模块。

注意:我知道“self”在其他语言中等同于“this”,以及“self”如何在类/对象上运行,但是在模块/库的上下文中,“self”没有任何意义。那么在没有类的模块之类的东西中,self 的上下文是什么?

最佳答案

在模块中:

当您在实例方法中看到 self 时,它指的是包含该模块的类的实例。

当您在实例方法之外看到 self 时,它指的是模块。

module Foo
  def a
    puts "a: I am a #{self.class.name}"
  end

  def Foo.b
    puts "b: I am a #{self.class.name}"
  end

  def self.c
    puts "c: I am a #{self.class.name}"
  end
end

class Bar
  include Foo

  def try_it
    a
    Foo.b # Bar.b undefined
    Foo.c # Bar.c undefined
  end
end

Bar.new.try_it
#>> a: I am a Bar
#>> b: I am a Module
#>> c: I am a Module

关于ruby-on-rails - (Ruby,Rails)模块和库中 SELF 的上下文......?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963378/

相关文章:

javascript - Dojo访问js文件之外的js对象

c++ - 为什么在方法范围完成后 vector 内容会发生变化?

sql - 使用 pgsql/activerecord 进行队列分析

javascript - 提交表单时,在新选项卡上打开

ruby-on-rails - 为什么在这种情况下调试不起作用?

ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型

ruby-on-rails - 未找到 Ruby gems,但已安装

ruby - ruby on rails 中的 Facebook 重定向 url 打开 ssl 错误

c++ - 在使用 GLUT 时避免使用全局变量

ruby - 逐行连接两个多行字符串