33
32

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 5 years have passed since last update.

[Ruby] Pry $(show-source/show-method) の使い方

Posted at

Pryではクラス、モジュール、メソッドの定義をみることができる。
使うコマンドはshow-sourceshow-method$も使うことができる)。
ドキュメントはこちら

サンプル用のコードpry_show_source.rbを作成

pry_show_source.rb
def hello_world
	p 'hello_world'
end

class MyClass
	class << self
		def hello_world
			p 'hello_world in MyClass class'
		end

		def goodbye
			p 'goodbye in MyClass class'
		end
	end

	def hello_world
		p 'hello_world in MyClass instance'
	end
end

require 'pry'
binding.pry
$ ruby pry_show_source.rb

##メソッドの定義を見る
メソッド定義を確認するにはshow-source method-nameとうつ。

[] pry(main)> show-source hello_world
# =>
From: pry_show_source.rb @ line 1:
Owner: Object
Visibility: private
Number of lines: 3

def hello_world
        p 'hello_world'
end

cdでクラスの中に入ってからshow-sourceすると、クラス内でメソッドを探してくれる。インスタンスメソッド、クラスメソッドの両方を探索するが、インスタンスメソッドが優先される。

[] pry(main)> cd MyClass
[] pry(MyClass):1> show-source hello_world
# =>
From: pry_show_source.rb @ line 16:
Owner: MyClass
Visibility: public
Number of lines: 3

def hello_world
        p 'hello_world in MyClass instance'
end

[] pry(MyClass):1> show-source goodbye
# =>
From: pry_show_source.rb @ line 11:
Owner: #<Class:MyClass>
Visibility: public
Number of lines: 3

def goodbye
        p 'goodbye in MyClass class'
end

class#methodでインスタンスメソッドを指定したり、object.methodでオブジェクトのメソッド(クラスメソッド)を指定することもできる。

[] pry(MyClass):1> exit
=> MyClass
[] pry(main)> show-source MyClass#hello_world
# =>
From: pry_show_source.rb @ line 16:
Owner: MyClass
Visibility: public
Number of lines: 3

def hello_world
        p 'hello_world in MyClass instance'
end

[] pry(main)> show-source MyClass.hello_world
# =>
From: pry_show_source.rb @ line 7:
Owner: #<Class:MyClass>
Visibility: public
Number of lines: 3

def hello_world
        p 'hello_world in MyClass class'
end

##クラスやモジュールの定義を見る
クラス定義を確認するにはshow-source class-nameとうつ。

[] pry(MyClass):1> show-source MyClass
# =>
From: pry_show_source.rb @ line 5:
Class name: MyClass
Number of lines: 15

class MyClass
        class << self
                def hello_world
                        p 'hello_world in MyClass class'
                end

                def goodbye
                        p 'goodbye in MyClass class'
                end
        end

        def hello_world
                p 'hello_world in MyClass instance'
        end
end
33
32
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
33
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?