Reputation: 12222
Is there a way to get a true proc
from a method in Ruby?
An UnboundMethod
obtained via instance_method
does not fit the bill because I can only bind it to an object of the class that declared the method. I can't reinterpret self
inside the method body the way I could in a proc
(using instance_exec
).
Similarly, a Method
obtained via method
is not okay, because self
is bound to the receiver of method
and I cannot change it.
Edit (Clarification):
What I'm trying to do is to take a method defined in one class and transfer it to another class. This means I need to be able to reinterpret the meaning of self
within the method. For proc
s, this is possible via instance_exec
and instance_eval
, but not for methods.
Why I am trying to move methods from one class to another? Long story short, to implement a form of namespacing, as I am most displeased with the visibility control provided by Ruby (there is no way to hide a module member to an including class). This is however far beyond the scope of this question.
Upvotes: 2
Views: 119
Reputation: 21791
Maybe to_proc
from Method
can help you:
class A
def test
puts 'this is a test'
end
end
m = A.new.method(:test)
m.to_proc.call #=> this is a test
UPDATE: Just an idea
By using sourcify gem convert proc
from first object to source, and then evaulate it in the context of second object
Upvotes: 4