Last active
July 6, 2019 11:37
-
-
Save TomohikoSato/df6812adf73cadfb6fef4ffd977012a1 to your computer and use it in GitHub Desktop.
rubyの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
# https://qiita.com/creamysellotape/items/68a7203bae7296707d43#comment-29e1991a2d2263d466ef | |
# 「メソッド実行中は常に自分自身(メソッドが呼び出されたインスタンス)が 誰であるかという情報が保存されており、selfでその情報を取ることができる。」 | |
# Class.new で渡されるブロックの引数はnewで生成するクラスになる https://docs.ruby-lang.org/ja/latest/method/Class/s/new.html | |
# トップレベルの文脈 | |
p self #=> main | |
class Foo | |
# クラス定義の文脈 | |
p self #=> Foo | |
def foo | |
# メソッド定義の文脈 | |
p self | |
end | |
end | |
Foo.new.foo #=> #<Foo:0x007f8d691e40d0> | |
Foo = Class.new do | |
# クラス定義の文脈 | |
p self #=> <Class:0x00007fb69f062298> | |
def foo | |
# メソッド定義の文脈 | |
p self | |
end | |
end | |
Foo.new.foo #<Foo:0x00007fb69f061b90>Foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment