Re-binding Proc

P

Phrogz

Is there a way to call a proc while passing in the binding/scope for
'self'? I found an un-responded-to question on this (ruby-talk:12794)
in 2001 which implies that, at least then, there was no way to do it.

What I'm doing:
class Foo
@@handlers = {}

def self.handle_type( type, &proc )
@@handlers[ type ] = proc
end

attr_reader :name
def initialize( name )
@name = name
end

def do_thing( type )
@@handlers[ type ].call( self )
end
end

Foo.handle_type( :showname ){ |me|
puts "My name is '#{me.name}'"
}

f = Foo.new( 'f' )
f.do_thing( :showname )
#=> My name is 'f'


What I'd like to do instead:

Foo.handle_type( :showname ){
puts "My name is '#{self.name}'"
}
 
P

Phrogz

Damn, hit send too soon. **continues**

I realize that I can do this by defining a method (as below), but for
some reason that feels bad to me. I'd like to do it with Proc objects,
if possible.

# Works by spamming the method namespace.
class Foo
def self.handle_type( type, &proc )
define_method( "dothing_#{type}", &proc )
end
# ...
def do_thing( type )
send "dothing_#{type}"
end
end
 
E

Eero Saynatkari

Phrogz said:
Is there a way to call a proc while passing in the binding/scope for
'self'? I found an un-responded-to question on this (ruby-talk:12794)
in 2001 which implies that, at least then, there was no way to do it.

I may be just feeling light-headed from COBOL, but
would #instance_eval not work here?
What I'm doing:
class Foo
@@handlers = {}

def self.handle_type( type, &proc )
@@handlers[ type ] = proc
end

attr_reader :name
def initialize( name )
@name = name
end

def do_thing( type )
@@handlers[ type ].call( self )

instance_eval &@@handlers[type]
end
end

Foo.handle_type( :showname ){ |me|
puts "My name is '#{me.name}'"
}

Foo.handle_type:)showname) {puts "My name is #{self.name}"}
 

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

Similar Threads

Deferring proc bindings 2
Python battle game help 2
about lambda and its binding 3
Late binding Method 0
Proc comparison 9
Proc rebinding 1
Instance Eval of a Proc 10
Comparing Proc Objects? 1

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,112
Latest member
VinayKumar Nevatia
Top