InfoQ

News

Ruby 1.9 with Symbol#to_proc and (soon) curried Procs

Posted by Werner Schuster on Feb 26, 2008

Community
Ruby
Topics
Programming ,
Language
Tags
Languages ,
Language Features ,
Ruby1.9
Next to Ruby 1.9's big new features such as threading changes or Fibers, it also added a host of smaller utility functions to the standard library. We already mentioned the Object.tap method, which adds a convenient way of spying on chained method calls.

Similarly to the tap method, the idea for the to_proc has been known in the Ruby community for some time - the feature is also available for pre-1.9 Ruby versions. Ruby 1.9 simply integrates this into the class Symbol, making the behavior available without any supporting libraries.

Reg Braithwaite gives a quick introduction to how to_proc makes code like (1..100).inject(&:+) work:
The & operator converts Proc objects into blocks and block into Proc objects. In this case, it tries to convert the symbol :+ into a block. The conversion uses Ruby's built-in coercion mechanism. That mechanism checks to see whether we have a Proc object. If not, it sends the #to_proc method to the argument to make a Proc. If the Symbol :+ has a #to_proc method, it will be called. In Ruby 1.9 it has a #to_proc method. That method returns a Proc that takes its first argument and sends the + method to it along with any other arguments that may be present.
So, &:+ really means { |x, y| x + y }.
This beheavior can be seen with code like this.:
plus = :+.to_proc
puts plus.call(1,2) # prints '3'
Since the class Symbol has the to_proc method, this approach works for every symbol:
to_s = :to_s.to_proc
to_s.call(42) # results in the string "42"

The implementation of to_proc is simple. Dave Thomas (PragDave) shows how it works:
def to_proc
 proc { |obj, *args| obj.send(self, *args) }
end
It creates a Proc which, when called on an object, sends that object the symbol itself. So, when names.map(&:upcase) starts to iterate over the strings in names, it'll call the block, passing in the first name and invoking its upcase method.

While the feature might yield very succinct code, one question still remains: does this improve the readibility of code? The answer to this has probably changed with the addition of to_proc to standard Ruby 1.9, simply because the Symbol now always comes with to_proc.
 Previously, the availability of the method depended on whether some code or library had opened Symbol and added it. Also: understanding the code involved knowledge of the general Symbol#to_proc idiom, which in Ruby 1.9 has been officially added, and is now more likely to be mentioned in documentation.

This still leaves the question:
 (1..100).map(&:to_s) 
Vs.
 (1..100).map{|x| x.to_s } 
Saving five characters (for this example) - is it worth the extra complexity or not?

Another feature involving Procs has been added to Ruby 1.9 - albeit only in a very recent revision: Proc#curry. A recent ruby-core discussion shows what Proc#curry does:
 It's not difficult at all,
 proc {|x, y, z| x + y + z }.curry
 returns the proc object equivalent to
 proc {|x| proc {|y| proc {|z| x + y + z } } }

The name of this method stems from the concept of Currying, which:
[..] is the technique of transforming a function that takes multiple arguments into a function that takes a single argument (the other arguments having been specified by the curry).
In other words: using currying, a Proc that takes x arguments, can be called with a single argument. Since, obviously, it can't return the result of it's code - it's missing arguments required to run the code - it returns a new Proc that takes (x - 1) arguments. Once this has been repeated enough times so the resulting Proc has all the arguments it needs, the code is evaluated and the result returned.

An example what this can be used for from the same ruby-core thread:
plus_five = proc { |x,y,z| x + y + z }.curry.call(2).call(3) 
plus_five[10] #=> 15
Note: plus_five is a Proc - the [] operator for Proc is overloaded to invoke the Proc.

Caution: Proc#curry is a very recent addition to Ruby 1.9 - to try it, you'll have to use a recent revision.

No comments

Watch Thread Reply

Educational Content

Brian Marick on 4 Challenges and 5 Guiding Values of Agile Software Development

Brian Marick takes us through a quick tour of the most important values and challenges to adopting Agile successfully (they aren't the typical challenges and values we hear in the community).

Are You a Software Architect?

The line between development and architecture is tricky. Does it exist at all? Is an ivory tower actually needed? There's a balance in the middle, but how do you move from developer to architect?

Agile – A Way of Life and Pragmatic Use of Authority

The word 'authority' sometimes produces an allergic response in hard-line agilists. Freedom and authority – both are bad if misused and both are good if used in right spirit for a noble cause.

Getting Started with Grails, Second Edition

"Getting Started with Grails" brings you up to speed on this modern web framework. Companies as varied as LinkedIn, Wired, and Taco Bell are all using Grails. Are you ready to get started as well?

Using ITIL V3 as a Foundation for SOA Governance

Those familiar with only ITIL V2 often scoff at the thought that ITIL could serve as a governance framework for SOA. With ITIL V3, the focus of the framework shifted towards service-orientation.

Adrian Colyer on AspectJ, tc Server and dm Server

SpringSource CTO Adrian Colyer discusses AspectJ, SpringSource's dm Server and tc Server products, OSGi and Scrum.

Adam Wiggins on Heroku

Heroku's Adam Wiggins talks about Rails, Background Jobs, Add-Ons, Ruby, and how Heroku manages to work around Ruby's inefficiencies using Erlang and other languages.

SOA as an Architectural Pattern: Best Practices in Software Architecture

For Grady Booch the foundation of a good architecture is patterns, SOA being just one of many patterns. In this Second Life presentation, Booch attempts to bring more clarity on what architecture is.