Provide value for self when using Proc#call

Viewed 6639

When using Proc#call to call a lambda function in Ruby, self always ends up with the value that it had when the function was defined, rather than the value it has when the function is called, for example:

$p = lambda { self }

class Dummy
  def test
    $p.call
  end
end

d = Dummy.new

> d.test
=> main

Calling test returns main, when what I intended it to return is #<Dummy:0xf794> - an instance of Dummy, which was the value of self at the point in the code where I called $p.

In Javascript, I would just pass the object that I want to be the "callee" as the first argument to call. Is there any such functionality in Ruby, allowing me to set an arbitrary object, or at least the current value of self, as the new value for self when I call a Proc?

3 Answers

You may want to use instance_exec because it allows you to pass arguments to the block whereas instance_eval does not.

def eval_my_proc_with_args(*args, &block)
  instance_exec(*args, &block)
end
Related