Feature #22486
closedAnonymous method
Description
I propose an API Method.new(receiver, name = nil, &block) to define an anonymous singleton method and UnboundMethod.new(owner, name = nil, &block) to define an anonymous instance method. The default value of name can be :anonymous for compatibility concern (existing code bases may have been assuming Method#name is not nil). This functionality can currently be achieved in pure Ruby as follows:
def Method.new receiver, name = :anonymous, &body
old = begin
receiver.singleton_method name
rescue NameError
nil
end
receiver.define_singleton_method name, &body
result = receiver.method name
if old
receiver.define_singleton_method name, old
else
receiver.singleton_class.undef_method name
end
result
end
def UnboundMethod.new owner, name = :anonymous, &body
old = begin
owner.instance_method name
rescue NameError
nil
end
owner.define_method name, &body
result = owner.instance_method name
if old
owner.define_method name, old
else
owner.undef_method name
end
result
end
A use case is when one wants to pass a block with a block argument to instance_exec. For example:
Updated by matz (Yukihiro Matsumoto) 9 days ago
- Status changed from Open to Rejected
In Ruby, the role of an anonymous method is played by Proc. I don't want to introduce another kind of anonymous callable.
What you are missing is a way to call a Proc with a different self while also passing a block to it. That is a limitation of instance_exec, and if it needs to be solved, it should be solved for Proc, not by adding anonymous methods.
For now, you can do this without defining anything on the receiver:
um = Module.new { define_method(:call, &body) }.instance_method(:call)
um.bind_call(obj, *args, &blk)
So I am not going to accept this proposal.
Matz.