LoginSignup
5
6

More than 1 year has passed since last update.

Ruby: 絶対パスでメソッドを呼び出す。

Last updated at Posted at 2015-09-15

メソッドの呼び出し。

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オープンチャットもご利用ください。

メンター受付

5
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6