tags:

views:

297

answers:

1

Hi All,

Is it possible to execute a proc within the context of another object?

I know that normally you'd do proc.call(foo), and then the block should define a parameter. I was wondering though whether I could get "self" to bind to foo so that it's not necessary to have a block parameter.

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
+8  A: 
foo.instance_eval &proc

instance_eval can take a block instead of a string, and the & operator turns the proc into a block for use with the method call.

Chuck
Squeegy