This post originated from an RSS feed registered with Ruby Buzz
by Jan Lelis.
Original Post: Become a Proc Star!
Feed Title: rbJ*_*L.net
Feed URL: http://feeds.feedburner.com/rbJL
Feed Description: Hi, I am a fan of Ruby and like to explore it and the world around ;).
So I started this blog, where I am publishing code snippets, tutorials for beginners as well as general thoughts about Ruby, the web or programming in general.
One useful (and funny) feature of Ruby is the Symbol#to_proc method that lets you write concise code like this: %w|1 2 3 4|.map(&:to_i). Almost everyone who knows this feature loves it ;). However, the use cases are pretty limited, because in most cases you need to pass parameters!
Luckily, there is a pretty simple solution: symbols are not the only type that supports turning into a proc. Actually, every class is able to, it just needs to implement the to_proc method ;).
Array
Let’s do this with Array (as done here) – now we are able to pass parameters:
# If the object is found as key in the hash, this runs its value as proc,# else it just returns the object.class Hashdef to_procProc.new{|obj|ifself.member?objself[obj].to_proc.callobjelseobjend}endend# usage# [1,2,3,4,5].map &{ 1 => :to_s,# 3 => [:to_s, 2] } # if you use Array#to_proc# => ["1", 2, "11", 4, 5]