Function Object - in Ruby

In Ruby

In Ruby, several objects can be considered function objects, in particular Method and Proc objects. Ruby also has two kinds of objects that can be thought of as semi-function objects: UnboundMethod and block. UnboundMethods must first be bound to an object (thus becoming a Method) before they can be used as a function object. Blocks can be called like function objects, but to be used in any other capacity as an object (e.g. passed as an argument) they must first be converted to a Proc. More recently, symbols (accessed via the literal unary indicator :) can also be converted to Procs. Using Ruby's unary & operator—equivalent to calling to_proc on an object, and assuming that method exists—the Ruby Extensions Project created a simple hack.

class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } end end

Now, method foo can be a function object, i.e. a Proc, via &:foo and used via takes_a_functor(&:foo). Symbol.to_proc was officially added to Ruby on June 11, 2006 during RubyKaiga2006.

Because of the variety of forms, the term Functor is not generally used in Ruby to mean a Function object. Just a type of dispatch delegation introduced by the Ruby Facets project is named as Functor. The most basic definition of which is:

class Functor def initialize(&func) @func = func end def method_missing(op, *args, &blk) @func.call(op, *args, &blk) end end

This usage is more akin to that used by functional programming languages, like ML, and the original mathematical terminology.

Read more about this topic:  Function Object

Famous quotes containing the word ruby:

    Its quick silver bell beating, beating
    And down the dark one ruby flare
    Pulsing out red light like an artery,
    Karl Shapiro (b. 1913)

    A man in the house is worth two in the street.
    Mae West, U.S. actor, screenwriter, and Leo McCarey. Ruby Carter (Mae West)