Andreas Otto
Andreas Otto

Reputation: 329

Ruby: how I get the instance from an bound method

in ruby I can bind a method to a receiver (instance):

class TEST
  def meth
  end
end
bound_method = TEST.new.method(:meth)

Question: How I can get the reveiver from a bound method back?

possible solution, found in docs:

/*
 *  call-seq:
 *     binding.receiver    -> object
 *
 *  Returns the bound receiver of the binding object.
 */
static VALUE
bind_receiver(VALUE bindval)
{
    const rb_binding_t *bind;
    GetBindingPtr(bindval, bind);
    return vm_block_self(&bind->block);
}

Upvotes: 0

Views: 63

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

How I can get the reveiver from a bound method back?

If you take a look at the documentation of Method, you will find the method Method#receiver, which returns the bound receiver of the Method object:

receiverobject

Returns the bound receiver of the method object.

(1..3).method(:map).receiver # => 1..3

Upvotes: 2

Related Questions