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

method =
p method # => #<Method: A#hi>
p # => 'A#hi'

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

class Cow
  def moo
    'A method'

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

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s