Inspecting Method Source Code in Ruby
Ruby provides tools to access the source code of methods directly in the console. This is useful for debugging or understanding external libraries. Note: methods defined dynamically (common in Rails) might not expose their source.
Viewing Instance Method Source
To inspect an instance method, use instance_method
on the class, followed by source
:
Product.instance_method(:calculate_price).source
# => " def calculate_price\n base_price * discount_factor\n end\n"
To improve readability, call display
:
Product.instance_method(:calculate_price).source.display
# def calculate_price
# base_price * discount_factor
# end
# => nil
Viewing Class (Singleton) Method Source
For class methods, replace instance_method
with singleton_method
:
Product.singleton_method(:find_by_sku).source
# => " def find_by_sku(sku)\n where(sku: sku).first\n end\n"
Finding Methods Dynamically
If you’re unsure about a method’s name, filter methods using a regular expression.
Instance Methods
To list instance methods matching a pattern:
Order.instance_methods.grep(/total/)
# => [:calculate_total, :total_in_cents]
This finds all methods with “total” in their name.
Class Methods
For class methods, use singleton_methods
with a regex:
Order.singleton_methods.grep(/export/)
# => [:export_to_csv, :export_to_pdf]