Re-naming a block

A

Andrew Wagner

[Note: parts of this message were removed to make it a legal post.]

Hi all.

I'm writing a method which takes a block and returns a lambda which will
execute that block when called. Here's the code:

def foo &block
Proc.new { yield }
end

a = foo { 3 }
puts a


This returns something like #<Proc:[email protected]:2 (lambda)>. That's
all well and good, but what I'd really like is for that line number to show
up as 5, since that's where the block is actually defined. So I try this:

def foo &block
a = Proc.new { yield }
def a.to_s
block.to_s
end
a
end

a = foo { 3 }
puts a

But here, ruby tells me that 'block' is undefined inside a's to_s. It's
clearly not creating the closure I'd hoped for. I've played around with a
few variations, but can't seem to get it to do what I want. Suggestions?
 
J

Jesús Gabriel y Galán

Hi all.

I'm writing a method which takes a block and returns a lambda which will
execute that block when called. Here's the code:

def foo &block
=A0Proc.new { yield }
end

a =3D foo { 3 }
puts a


This returns something like #<Proc:[email protected]:2 (lambda)>. Tha= t's
all well and good, but what I'd really like is for that line number to sh= ow
up as 5, since that's where the block is actually defined. So I try this:

def foo &block
=A0a =3D Proc.new { yield }
=A0def a.to_s
=A0 =A0block.to_s
=A0end
=A0a
end

a =3D foo { 3 }
puts a

But here, ruby tells me that 'block' is undefined inside a's to_s. It's
clearly not creating the closure I'd hoped for. I've played around with a
few variations, but can't seem to get it to do what I want. Suggestions?

def creates a new scope, not a closure. Try define_method:

def foo &block
a =3D Proc.new {yield}
class << a; self; end.send:)define_method, :to_s) {block.to_s}
a
end

Jesus.
 
R

Rick DeNatale

def foo &block
=A0Proc.new { yield }
end

a =3D foo { 3 }
puts a

Well maybe the answer is to create a proc with the right line number
from the beginning:

def foo &block
Proc.new(&block)
end

a =3D foo { 3 }
puts a

puts a.call

#<Proc:0x000000010012e688@untitled:5>
3



--=20
Rick DeNatale

Help fund my talk at Ruby Conf 2010:http://pledgie.com/campaigns/13677
Blog: http://talklikeaduck.denhaven2.com/
Github: http://github.com/rubyredrick
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
 

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

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top