From: "UlyssesZhan (Ulysses Zhan) via ruby-core" Date: 2026-10-29T05:51:22+00:00 Subject: [ruby-core:127274] [Ruby Feature#22486] Anonymous method Issue #22486 has been reported by UlyssesZhan (Ulysses Zhan). ---------------------------------------- Feature #22486: Anonymous method https://bugs.ruby-lang.org/issues/22486 * Author: UlyssesZhan (Ulysses Zhan) * Status: Open ---------------------------------------- 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/