メソッドの呼び出し。
Book.example
絶対パスだと、次のように書ける。
::Book.example
たとえばモジュールの内部から、同名のクラスを呼び出す場合に役立つ。
book.rb
class Book
def self.example
p 'Class'
end
end
module Example
class Book
#このモジュールの example を呼ぶ
def self.call_module_method
Book.example
end
# 普通のClass の example を呼ぶ
def self.call_class_method
::Book.example
end
def self.example
p 'Module'
end
end
end
Example::Book.call_module_method
Example::Book.call_class_method
実行結果
"Module"
"Class"
- 「絶対パス」という呼び方が正しいかどうか分からないが、ググるときにキーワードが分からなくて苦労したのでメモ。
-
Class::Book.example
でも呼べるかと思ったが違った。( Class の部分が無視される )
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
メンター受付