liveBook · Manning

Function

As explained in The Well-Grounded Rubyist, Fourth Edition

A function is a callable computation that can be passed as a value or returned as a value in a functional programming style.

A function is a callable computation that can be passed as a value or returned as a value. In Ruby, blocks and Proc objects provide this functional style: methods can accept transformation instructions, return procs, or do both. section 16.3 section 16.3.4

Passing and returning transformations

Mapping passes a block into a method and returns a new array: [1,3,5].map { |x| x * 5 } produces [5, 15, 25]. A method can instead return a reusable computation: multiply_by(10) returns a proc, and calling that proc with 12 performs the later transformation. section 16.3

Functions become more flexible when their arguments can be supplied incrementally.

  • Partial function application supplies fewer arguments than a function's arity and returns one function accepting the remainder. section 16.3.5
  • Currying turns a multi-argument function into a sequence of functions, each accepting another argument; Ruby's curry method supports both patterns. section 16.3.5
def multiply_by(m)
  Proc.new { puts it * m }
end
mult = multiply_by(10)
mult.call(12)      

Trace a method that captures a multiplier in a returned Proc, then call the resulting function with a later argument. section 16.3.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains blocks, procs, arity, partial application, and currying with runnable examples, while stopping short of implementation internals.
Examples
Demonstrates map transformations, returned multiplier procs, curried addition, and generic functions selecting array multiples.
What it assumes
Assumes familiarity with Ruby methods and blocks while developing Proc-based functions, argument arity, and functional application.
What you can do after
Apply it via Ruby blocks, Proc objects, lambdas, and curry to pass transformations or build reusable specialized functions.
How it connects
Connects functions with higher-order functions, blocks, Proc objects, lambdas, map, reduce, partial function application, and currying.

Also explained in

Compare how 20 books explain function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.