1

In other languages I have seen ways of showing the code that makes up a function or method. Is there a way to do this in the IRB?

Example, in R, you can simply type a function without the () and it will tell you what code will run when the function is called. Simple example here

Is this possible in IRB? (preferably without pry or any other gems)

stevec
  • 41,291
  • 27
  • 223
  • 311
  • 1
    https://stackoverflow.com/questions/3393096/how-can-i-get-source-code-of-a-method-dynamically-and-also-which-file-is-this-me/46966145#46966145 – mrzasa Jan 29 '19 at 16:35
  • @mrzasa I dropped the code blocks into irb and the first one errors with `TypeError (no implicit conversion of nil into String)`. The second one doesn't error. But when I call `.source` on an existing method, it errors. E.g. `class.method` and `"class".method` both error. – stevec Jan 30 '19 at 18:40
  • @mrzasa I guess what I'm saying is I can read the answer but I don't know what to actually do with it. Do I copy the code into irb? Can you give an example of how to call the method? – stevec Jan 30 '19 at 18:48

1 Answers1

0

Quoting https://stackoverflow.com/a/46966145/580346:

method = SomeConstant.method(:some_method_name)
file_path, line = method.source_location
# puts 10 lines start from the method define 
IO.readlines(file_path)[line-1, 10]

If you want use this more conveniently, your can open the Method class:

# ~/.irbrc
class Method
  def source(limit=10)
    file, line = source_location
    if file && line
      IO.readlines(file)[line-1,limit]
    else
      nil
    end
  end
end

Paste above code to your irb and then call YourConstant.method(:your_method).source

mrzasa
  • 22,895
  • 11
  • 56
  • 94