ruby – How to check the source code of the defined method with pry etc.

Question: Question:

In Ruby, for example, by using Method.source_location , you can check the file path and the number of lines where the method is defined.

However, if you want to go a little further and check not only the definition location but also the actual behavior of the method, that is, the source code itself on the spot, there is a way to browse the source when it is actually defined by pry etc. Is it there?

Answer: Answer:

I think it is possible if you use show-source with pry.

[1] pry(main)> show-source Pry

From: /var/lib/gems/1.9.1/gems/pry-0.10.1/lib/pry/pry_instance.rb @ line 24:
Class name: Pry
Number of monkeypatches: 6. Use the `-a` option to display all available monkeypatches
Number of lines: 641

class Pry
  attr_accessor :binding_stack


[2] pry(main)> show-method pry

From: /var/lib/gems/1.9.1/gems/pry-0.10.1/lib/pry/core_extensions.rb @ line 41:
Owner: Object
Visibility: public
Number of lines: 7

def pry(object=nil, hash={})
  if object.nil? || Hash === object
    Pry.start(self, object || {})
    Pry.start(object, hash)

Also, $ is defined as an alias, so you can use that as well.

[3] pry(main)> require 'rexml/document'
=> true
[4] pry(main)> $ REXML::Document

From: /usr/lib/ruby/1.9.1/rexml/document.rb @ line 20:
Class name: REXML::Document
Number of lines: 226

class Document < Element
  # A convenient default XML declaration.  If you want an XML declaration,
  # the easiest way to add one is mydoc << Document::DECLARATION
Scroll to Top