Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Object#singleton_method

(::interned name) -> ::Method
obj.singleton_method(sym) → method

Similar to method, searches singleton method only.

Example
class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
def k.hi
  "Hi, @iv = #{@iv}"
end
m = k.singleton_method(:hi)
m.call   #=> "Hi, @iv = 99"
m = k.singleton_method(:hello) #=> NameError

Ruby version changes

  1. 3.4
    • Object#singleton_method now returns methods in modules prepended to or included in the receiver’s singleton class. [Bug #20620]

      Example
      o = Object.new
      o.extend(Module.new{def a = 1})
      o.singleton_method(:a).call #=> 1