rubymetaprogrammingsingleton-methods

Ruby: execute singleton method in different context


(edited to make question more specific)

I would like to know if it's possible to execute a singleton method in the context of another object as in the following example:

class A
  def initialize
    @foo = 'foo'
  end
end

def A.singleton(*args)
  puts 'in singleton'
  puts @foo
end

A.new.instance_eval &A.method(:singleton)

# output is:
# - in singleton

# desired output:
# - in singleton
# - foo

Solution

  • This is not possible. In fact Ruby has a specific error for when you try to do so:

    module Foo
      def self.bar
      end
    end
    
    class Baz
    end
    
    Foo.method(:bar).unbind.bind(Baz.new)
    # TypeError: singleton method called for a different object
    

    This really is an artificial restriction, since UnboundMethod#bind could easily just skip the type check and let you do it. But it would be a fundamental contradiction if you could call a singleton method with a different receiver: a singleton method is defined for a single instance. It makes sense that this isn't allowed.