Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 134 ยท Methods and Blocks

Method Objects, Currying and Composition

Treat methods as values in Ruby. Learn Method and UnboundMethod, bind, super_method, curry, partial application and composing functions with >> and <<, with runnable examples.

In Ruby you usually call a method and get its result. But a method can also be held in your hands as a value: stored in a variable, passed to another method, inspected, borrowed by a different object, or combined with other methods into a new one. The objects that make this possible are Method and UnboundMethod, and the techniques built on them are called currying and function composition.

The lesson Procs and Lambdas introduced curry, >> and method(:name) briefly. Here we slow down and go deeper. You will learn what a method object really contains, how UnboundMethod lets you take a method away from its class, how to specialize functions by fixing arguments one at a time, and how to assemble small functions into pipelines without writing a single def. If blocks and closures are new to you, read Blocks and Closures and Binding first.

The Method object

Calling object.method(:name) returns a Method: the method together with the receiver it was taken from. It behaves like a lambda that remembers self.

classDiagram
  class Object {
    +method(name) Method
  }
  class Method {
    +call(args)
    +receiver
    +owner
    +arity
    +parameters
    +unbind() UnboundMethod
    +to_proc() Proc
    +curry(n)
    +super_method()
  }
  class UnboundMethod {
    +bind(object) Method
    +bind_call(object, args)
    +name
    +owner
  }
  Object --> Method : obj.method(:name)
  Method --> UnboundMethod : unbind
  UnboundMethod --> Method : bind

A Method is tied to a receiver; an UnboundMethod is the same code without one, which you can bind to another compatible object.

A method object can be inspected and called in several equivalent ways:

Ruby Inspecting and calling a Method object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The numbers and shapes are worth reading carefully. arity is -1 because there is one optional positional argument, and parameters lists each parameter with its kind (:opt for optional, :key for an optional keyword). owner tells you which class or module actually defines the method, which is helpful when you wonder where an inherited method came from. call, .() and [] are three spellings of the same invocation.

You can also fetch a method with public_method (which refuses private ones) and use respond_to?(:name) to test first. For a method on main or a top-level helper, plain method(:name) works because it is looking at self.

Method objects as blocks

The & operator calls to_proc on its operand. Method#to_proc returns a lambda, so arguments are checked strictly. This is what makes the idiom map(&method(:name)) possible:

Ruby Passing methods where blocks are expected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Here 10.method(:+) is a method object bound to the number 10, so mapping it over a list adds 10 to every element. Method#=== calls the method with the tested value and checks the truthiness of the result, which is why a predicate method can sit in a when clause (see case/when).

UnboundMethod: a method without a receiver

SomeClass.instance_method(:name) or method_object.unbind gives an UnboundMethod. It is the code, detached from any object. To call it you must bind it to an object that is an instance of the original class (or, for methods from a module, any object at all). bind_call(object, *args) does the bind and the call in one step.

This is the tool for three jobs: calling the "real" implementation when an object has overridden it, wrapping an existing method, and borrowing a module's method.

Ruby UnboundMethod, bind_call and super_method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The second line is the surprising one: Kernel.instance_method(:class) is the original implementation from Kernel, bound to an object that has replaced class. The same trick is used by libraries that must call the real inspect or == on proxy objects. The wrapping example is a miniature of what profilers and test doubles do, and the safe, more common alternatives are Module#prepend and super (see Modules and Mixins and Hooks).

UnboundMethod#bind normally requires the object to be an instance of the class where the method was defined. A method taken from a module can be bound to any object, which is why Shout worked on a plain string.

Currying and partial application

A function of three arguments can be turned into a chain of three functions of one argument each. That is currying. Supplying arguments one or two at a time and getting back a new function that still waits for the rest is partial application. Ruby has this built in: lambda.curry, proc.curry and method.curry.

flowchart LR
  A["volume.curry"] -->|"[2]"| B["waits for width, height"]
  B -->|"[3]"| C["waits for height"]
  C -->|"[4]"| D["24"]
  B -->|"[3, 4] at once"| D

Each call supplies some arguments; once every required argument has arrived, the real method runs.

A curried callable accepts one argument or several at a time. When the total reaches the required count, it runs.

Ruby curry, partial application and arity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Partial application turns a general function into a specific, readable one. usd and yen come from the same formatter, with the currency and number of decimals fixed. A curried lambda keeps strict argument checking, while a curried proc is lenient, as described in Procs and Lambdas.

Currying fits best when the first arguments are the "configuration" and the last one is the "data". Order your parameters that way when you design a function you expect to curry. When you cannot reorder them, a plain lambda that calls the original does the same job: ->(x) { volume(10, 10, x) }.

Composition with >> and <<

Composition builds a new callable out of two. f >> g means "do f, then g" and f << g means "do g, then f". Both work with procs, lambdas and method objects, and with any object that responds to call. Because Symbol#to_proc makes a lambda too, symbols can join in.

Ruby Building pipelines without def

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice what the Prefixer example shows: >> is defined on Proc and Method, not on arbitrary objects. Your own object can be the argument, because only call is needed, but it cannot be the left side. If your class should start a composition, hand over its method (obj.method(:call)) or give it a to_proc. The left side of >> is what decides how the result behaves: proc >> callable keeps proc-ness, while method >> callable always returns a lambda.

Why compose?

Pipelines express what happens to the data in the order you read it. Each step is tiny, testable and reusable on its own. Ruby also has Object#then for the same flow with ordinary values (input.then(&parse).then(&double)), and Enumerable chains for collections. Pick the style your team can read at a glance, and do not hide complicated logic in a ten-step composition. When a pipeline is hard to follow, give the middle steps names with def.

Pitfalls to remember

  • Methods are bound to their receiver. obj.method(:name) keeps obj alive and calls on that object even if the variable changes later.
  • Method#to_proc is a lambda. map(&method(:puts)) works, but a method that takes two arguments will raise when mapped over single elements, unlike a proc that silently adjusts.
  • Arity matters for curry. Optional arguments are not counted; give the count explicitly with curry(n) when you need to.
  • Keyword arguments do not curry well. Curry positional arguments, and capture keywords in a closure or an ordinary lambda.
  • Do not overuse composition. If you need a debugger on every step, write a plain method.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "hello".method(:upcase) return?

    method returns a Method, which remembers its receiver. Call it with call, .() or [].
  2. 2. How do you call the original Kernel#class on an object that overrides class?

    instance_method gives the original UnboundMethod, and bind_call binds it to the object and calls it, bypassing the override.
  3. 3. Given add = ->(a, b, c) { a + b + c }, which call returns 6?

    A curried lambda collects arguments until it has three, then runs. Supplying 1 and then 2 and 3 gives 1 + 2 + 3.
  4. 4. What is the difference between f >> g and f << g?

    f >> g reads left to right, g.call(f.call(x)). f << g reads right to left, f.call(g.call(x)).
  5. 5. Which description of method(:name).to_proc is correct?

    Method#to_proc produces a lambda, which keeps the strict argument checking of the underlying method.

Summary

  • object.method(:name) returns a Method that remembers its receiver; inspect it with name, owner, receiver, arity, parameters and source_location, and call it with call, .() or [].
  • &method(:name) turns a method into a block (a lambda), and Method#=== lets a predicate method appear in case/when.
  • instance_method and unbind give an UnboundMethod; bind and bind_call attach it to another object, which is the way to reach an overridden original or wrap a method.
  • super_method finds the method that a method overrides.
  • curry and partial application fix arguments step by step; use curry(n) for variable arity and put the configuration arguments first.
  • >> and << compose procs, lambdas and methods; reduce(:>>) chains a list, and hashes and symbols join in through to_proc.

Next: Arrays