Ruby Tips - How to figure out where a method is defined

Ruby Tips - How to figure out where a method is defined

The other day when I was dabbling with the huge codebase, I was wondering where a particular method was being declared for a specific method
Software Development
by Jey Geethan | August 12, 2018

The other day when I was dabbling with the huge codebase, I was wondering where a particular method was being declared for a specific method. I wanted to know this because my greps didn't turn out to volatile and didn't return any results.

The Solution

The Ruby interpreter has certain methods that can be used for identifying under which module or class, the particular method is being defined. See the example below.

module Foo
  def say_hello
    puts "hello"
  end
end
	

class Bar
  include Foo
end
	

puts Bar.new.method(:say_hello)                   #=> #<Method: Bar(Foo)#say_hello>
puts Bar.new.method(:say_hello).source_location   #=> hello.rb


So using the .source_location you will be able to figure which file it has been declared.


Jey Geethan

Jey Geethan is a poet, author and an entrepreneur.


Related Articles

Software Development

Top 5 Tips for Software Development Managers To Conduct Effective 1 on 1s With Your Reports

by Jey Geethan | October 05, 2020
Top 5 Tips for Software Development Managers To Conduct Effective 1 on 1s With Your Reports
Some of the effective tips that can enhance your 1 on 1s with your reports. In 2020, software development is one of the major industries which provides millions of jobs. In fact, if you look at the statistics, this industry is poised to grow even further. According to Slashdata, it's expected to reach 45 million developers by 2030. As a manager, it's your responsibility that 1 on 1s are effective and help your reports. I want to talk about a few of the things that make this process really effective.
Software Development

iTerm2 vs Plain Old Terminal - Which One Is The Best?

by Jey Geethan | August 28, 2017
iTerm2 vs Plain Old Terminal - Which One Is The Best?
Have you ever wondered if you have an alternative that will be better and useful than the default terminal?