2009-02-08 7 views
26

È possibile eseguire un proc nel contesto di un altro oggetto?Binding of Procs

So che normalmente si farebbe proc.call (foo), e quindi il blocco dovrebbe definire un parametro. Mi chiedevo però se potevo ottenere da "me stesso" per legare a pippo in modo che non fosse necessario avere un parametro di blocco.

proc = Proc.new { self.hello } 

class Foo 
    def hello 
    puts "Hello!" 
    end 
end 

foo = Foo.new 

# How can proc be executed within the context of foo 
# such that it outputs the string "Hello"? 

proc.call 

risposta

41
foo.instance_eval &proc 

instance_eval può prendere un blocco invece di una stringa, e l'operatore & trasforma il proc in un blocco per l'utilizzo con la chiamata di metodo.

+0

'foo.instance_eval (e POC)' –

+0

Qualcuno può darmi un link documentazione per questo? Funziona sicuramente (ed è ** veramente ** fantastico), ma mi piacerebbe leggere i documenti. :) –

+1

@Josh Glover: http://www.ruby-doc.org/core-1.8.7/classes/Object.html#M000005 – Chuck

0

Questo è per Ruby 1.9:

class MyCat 
    def initialize(start, &block) 
    @elsewhere = start 
    define_singleton_method(:run_elsewhere, block) if block_given? 
    end 
end 
MyCat.new('Hello'){ @elsewehere << ' world' }.run_elsewhere