Created
January 2, 2019 19:24
-
-
Save havenwood/2d4cd1ac0cdcbfd61d77bda0ad81a373 to your computer and use it in GitHub Desktop.
An answer to a #ruby irc channel question about `self`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Right inside a class or module, `self` is the module or class itself. | |
module Same | |
def self.same | |
self == Same | |
end | |
end | |
Same.same | |
#=> true | |
# You can define a module method like this: | |
module Foo | |
def Foo.foo | |
:ok | |
end | |
end | |
Foo.foo | |
#=> :ok | |
# Instead of hardcoding `Foo`, we use `self` for less naming entanglment: | |
module Bar | |
def self.bar | |
:ok | |
end | |
end | |
# Another way to write that is: | |
module Baz | |
class << Baz | |
def baz | |
:ok | |
end | |
end | |
end | |
Baz.baz | |
#=> :ok | |
# Which again you'd use `self` with for easlier renaming without changes: | |
module Wombat | |
class << self | |
def wombat | |
:ok | |
end | |
end | |
end | |
Bar.bar | |
#=> :ok | |
# In the case of modules, you might consider #module_function instead: | |
module Example | |
module_function def example | |
:ok | |
end | |
end | |
Example.example | |
#=> :ok | |
# Using module_function will have the side effect of making the method private | |
# when it's included, which tends to be nice for extensibililty. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment