Accessing code blocks

  • Thread starter Grzegorz Dostatni
  • Start date
G

Grzegorz Dostatni

Cheers!

I need to do something silly. I need to access the code block as a
variable (to pass it - without evaluating - to another function). How can
I do that?

Is it possible for me to access the "text version of block?" Can I print
out the code that has been attached to my function instead of executing
it?

The only functions that work on code block (that I could find) are:
block_given? and yield. Obviously they do not fit the bill...

Please help.

Grzegorz Dostatni
 
B

Brian Candler

I need to do something silly. I need to access the code block as a
variable (to pass it - without evaluating - to another function). How can
I do that?

It's not silly at all, but the syntax isn't obvious if you haven't seen it
before.

At the end of your argument list give a named argument preceded with '&'.
This converts the block to an explicit Proc object which you can pass
around.

def function1(&blk)
function2(blk)
end

def function2(blk)
blk.call(99)
end

function1 { |i| puts i } #>> prints 99

Is it possible for me to access the "text version of block?" Can I print
out the code that has been attached to my function instead of executing
it?

No, decompiling blocks is not possible AFAIK :)

Regards,

Brian.
 
K

Kent Dahl

Grzegorz said:
Is it possible for me to access the "text version of block?" Can I print
out the code that has been attached to my function instead of executing
it?

As others have pointed out, this is not possible, atleast not without
jumping through hoops. If you don't mind jumping through hoops on the
caller side and a little uglier code, here is a quick stab I did at this
earlier:

class X
def first_definition( &binding )
@binding ||= binding
source = binding.call
redefine( source )
end
def redefine( source )
@source = source
@block = eval "Proc.new { #{source} }", @binding
end
def x(i)
@block.call(i)
end
end
x = X.new
a = 3
x.first_definition { %{|i|a+i} }
puts x.x(2) #=> 5
x.redefine %{|i|a-i}
puts x.x(2) #=> 1

Notice the syntax { %{|i|a+i} }
I wrap a string, "|i|a+i", inside a block. The block at this level only
serves as a binding, the contents of the string is used to create the
block itself. HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top