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

More than 1 year has passed since last update.

[備忘録]Ruby クラス内の変数とメソッドを調べる

Posted at

クラス内の変数とメソッドの調べ方についてまとめます

確認用のクラス(Suica)

class Suica
    DEFAULT_DEPOSIT = 500

    @@val1 = "class_variable"
    @@val2 = "class_variable"
    @val3 = 1
    attr_reader :money

    def initialize()
        @money = DEFAULT_DEPOSIT
    end

    public
    def charge(_money)
        @money += _money
    end

    private
    def spend(_money)
        @money -= _money
    end

    private
    def money
        @money
    end
end

変数を確認する

クラス変数:Class_variables
インスタンス変数:instance_variables

suica = Suica.new

puts "インスタンス変数一覧:suica.instance_variables"
puts suica.instance_variables

# => @money

puts "インスタンス変数一覧:class.instance_variables"
puts Suica.instance_variables
puts suica.class.instance_variables

# => @val3

puts "クラス変数一覧:class.class_variables"
puts Suica.instance_variables
puts suica.class.class_variables

# => @@val1
# => @@val2

メソッドを確認する(Public, Private, Protected)

Public: .public_methods
Private: .private_methods
Protected: .protected_methods

puts "public method一覧:suica.public_methods"
puts suica.public_methods

puts "private method一覧:suica.private_methods"
puts suica.private_methods

puts "protected method一覧:suica.protected_methods"
puts suica.protected_methods

参考ページ

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