Ruby’s Method Class

Ruby methods can be accessed as objects that are bound to a class. Methods aren’t technically objects in Ruby, but you can wrap them in objects. The distinction doesn’t matter for this blog post – we’ll simply investigate how use Ruby method objects that are easily accessible as instances of the Method class.

class A
  def hi
    'A#hi'
  end
end

method = A.new.method(:hi)
p method # => #<Method: A#hi>
p method.call # => 'A#hi'

Method objects can be compared with other method object, called, and unbound from an object.

class Cow
  def moo
    'A method'
  end
end

c = Cow.new
method = c.method(:moo)
method == c.method(:moo) # => true
method.call # => 'A method'
unbound = method.unbind # => #<UnboundMethod: Cow#moo>
unbound.call # => error because UnboundMethod objects cannot be called
unbound.bind(c) # rebind the unbound method to the c object
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s