Ruby: How to get the default value of optional proc arguments Ruby: How to get the default value of optional proc arguments ruby ruby

Ruby: How to get the default value of optional proc arguments


Assuming the proc / lambda was defined in a file, you can use the source_location method to find the location of that file and the line number it was defined on.

2.2.0 (main):0 > OH_MY_PROC.source_location=> [  [0] "sandbox/proc.rb",  [1] 1]

With some help from File.readlines we can make a short method that when passed a proc / lambda can spit out the source line it was defined on.

def view_def proc_lambda  location = proc_lambda.source_location  File.readlines(location[0])[location[1]-1]end

In action it looks something like this

2.2.0 (main):0 > view_def OH_MY_PROC=> "OH_MY_PROC = Proc.new { |a, b=2, *c, &d| 42 }\n"2.2.0 (main):0 > view_def OH_MY_LAMBDA=> "OH_MY_LAMBDA = ->(a, b=2, *c, &d) { 42 }\n"

If you want to do the same for methods it becomes a bit more involved. In that case I recommend reading this blog post from the Pragmatic Studio blog: "View Source" On Ruby Methods