From: "matz (Yukihiro Matsumoto) via ruby-core" Date: 2026-11-19T07:46:58+00:00 Subject: [ruby-core:127618] [Ruby Feature#22486] Anonymous method Issue #22486 has been updated by matz (Yukihiro Matsumoto). 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: ```ruby 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. ---------------------------------------- Feature #22486: Anonymous method https://bugs.ruby-lang.org/issues/22486#change-120137 * Author: UlyssesZhan (Ulysses Zhan) * Status: Rejected ---------------------------------------- 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: ```ruby 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: ```ruby module DefExtend def def_extend name, &body define_method name do |first_arg, *args, **opts, &block| puts "called with #{first_arg}" Method.new(self, &body).(*args, **opts, &block) end end end class C extend DefExtend def_extend(:foo) { |&block| block.(2) } end p C.new.foo(1) { _1 * 2 } ``` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/