This article focuses on discussing find where a method is defined at runtime in ruby.
Using Method#source_location
Method#source_location method returns the source location (file name and line number) where a method is defined.
Syntax:
method(:method_name).source_location
Example:
In this example, we use Method#source_location to print the file name and line number where the greet
method is defined.
# Finding where a method is defined at runtime using Method#source_location
# Define a method called greet
def greet
puts "Geeksforgeeks"
end
# Print the source location of the greet method
puts greet.method(:greet).source_location.inspect
Output
Geeksforgeeks ["Solution.rb", 3]
Using Kernel#caller_locations
Kernel#caller_locations method returns an array of Thread::Backtrace::Location
objects representing the current execution stack. By inspecting the caller locations, we can determine where a method call originates.
Syntax:
caller_locations
Example:
In this example, We use caller_locations method to print the caller locations when bar
method is called from foo
.
# Finding where a method is defined at runtime using Kernel#caller_locations
# Define two methods, foo and bar
def geeks
forgeek
end
def forgeek
# Print the caller locations
puts caller_locations
end
# Call the foo method
geeks
Output
Solution.rb:4:in `geeks' Solution.rb:13:in `<main>'
Using Method#owner
Method#owner
method returns the module or class where the method is defined.
Syntax
method(:method_name).owner
Example:
In this example,we use Method#owner to print the owner module of the my_method
method, which is MyModule
.
# Finding where a method is defined at runtime using Method#owner
module MyModule
# Define a method called my_method within the module MyModule
def self.my_method
puts "Hello from MyModule!"
end
end
# Print the owner module of the my_method method
puts MyModule.method(:my_method).owner
Output
#<Class:MyModule>