Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== In Ruby == In [[Ruby (programming language)|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 <code>:</code>) can also be converted to <code>Proc</code>s. Using Ruby's unary <code>&</code> operator—equivalent to calling <code>to_proc</code> on an object, and [[duck typing|assuming that method exists]]—the [[Ruby Extensions Project]] [https://web.archive.org/web/20060425104650/http://blogs.pragprog.com/cgi-bin/pragdave.cgi/Tech/Ruby/ToProc.rdoc created a simple hack.] <syntaxhighlight lang="ruby"> class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } end end </syntaxhighlight> Now, method <code>foo</code> can be a function object, i.e. a <code>Proc</code>, via <code>&:foo</code> and used via <code>takes_a_functor(&:foo)</code>. <code>Symbol.to_proc</code> was officially added to Ruby on June 11, 2006, during RubyKaigi2006. [https://web.archive.org/web/20060820025032/http://redhanded.hobix.com/cult/symbolTo_procExonerated.html] 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 (programming)|delegation]] introduced by the [https://web.archive.org/web/20070107205748/http://facets.rubyforge.org/ Ruby Facets] project is named as Functor. The most basic definition of which is: <syntaxhighlight lang="ruby"> class Functor def initialize(&func) @func = func end def method_missing(op, *args, &blk) @func.call(op, *args, &blk) end end </syntaxhighlight> This usage is more akin to that used by functional programming languages, like [[ML (programming language)|ML]], and the original mathematical terminology.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)