1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Ruby]クラスメソッドと定数をprivateにする

Last updated at Posted at 2023-11-28

インスタンスメソッドをprivateにするには、class定義の中にprivate領域を作って、その中で定義します。

class C
    private

    def func
        "called"
    end
end

# private method `func' called
# pp C.new.func

特異メソッドや定数については、この方法が使えなかったため、記事としてまとめておきます。

クラス特異メソッド

private_class_method

private_class_methodメソッドを使ってprivateにします。

class C
    def self.get_const
        "const"
    end

    private_class_method :get_const
end

# private method `get_const' called for C:Class
# pp C.get_const

特異クラスのインスタンスメソッド

特異クラス定義内でprivateメソッドとして定義します。

class C
    class << self
        private

        def get_const
            "const"
        end
    end
end

# undefined method `get_const' for C:Class
# pp C.get_const

単純にprivate領域に特異メソッドを書く方法は失敗します。

class C
    private

    def self.get_const
        "const"
    end
end

pp C.get_const # => "const"

定数

private_constantメソッドを使ってprivateにします。

class C
    Const = "const"
    private_constant :Const
end

# private constant C::Constant referenced
# pp C::Const

単純にprivate領域で定数を書く方法は失敗します。

class C
    private
    Const = "const"
end

pp C::Const # => "const"
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?