(Ruby,Rails) Context of SELF in modules and libraries…?

瘦欲@ 提交于 2019-11-28 17:31:24

In a module:

When you see self in an instance method, it refers to the instance of the class in which the module is included.

When you see self outside of an instance method, it refers to the module.

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

For a short summary... http://paulbarry.com/articles/2008/04/17/the-rules-of-ruby-self

self is also used to add class methods (or static methods for C#/Java people). The following snippet is adding a method called do_something to the current class object (static)...

class MyClass
    def self.do_something   # class method
       # something
    end
    def do_something_else   # instance method
    end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!