0

Say I have this Ruby method:

def get_proc_from_block(&block)
  return block
end

Now if I call it with a block like this:

p = get_proc_from_block(&:length)

...is there any way for me to somehow inspect p and get the string "length" from it?

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • first of all, unless your function is part of a class, variable 'b' will be destroyed as soon as you leave the function, and second, there is no way of getting the length of a method at run-time because the interpreter converts you code to something like machine code that that interpreter understands. The only way to get the number of characters in that method is to parse the source file containing it. – Ionut Hulub Feb 28 '13 at 19:37
  • @IonutHulub: I realize `b` is only accessible within the scope of `store_block`; I meant to ask whether it could be inspected from within the method (I will update the question to clarify). However, I am skeptical of your second claim because of Ruby's dynamic nature. For example I could create a new class and define a `length` method on it, then call the block on an instance of this class and it would work. But perhaps you understand the way this works better than I do (in which case, a more in-depth answer would be much appreciated!). – Dan Tao Feb 28 '13 at 19:54

1 Answers1

0

Each of the following expressions result in the same regular proc:

get_proc_from_block(&:length)
:length.to_proc
proc{ |a| a.length }

And Ruby doesn't support inspecting their source code. For more detailed answers check out these questions:

Community
  • 1
  • 1
Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74