Symbol#to_proc
I’ve never seen anyone use this, only recently read about it when I came across a blog. It’s part of
Ruby/Extensions,
which has
some useful method definitions
,
as well as a few
cool but possibly evil
ones. The reason
Symbol#to_proc
is worth noting, though, is that it saves quite a bit of typing/punctuation for common tasks.
I think the examples from their docs sum up what it does the best:
%{john terry fiona}.map(&:capitalize) # -> %{John Terry Fiona}<br/> sum = numbers.inject(&:+)<br/>
The explanation is pretty simple: when you pass an object as a block, #to_proc is called on the object, just like the way #to_str is called when you try to concatenate a string with something, in order to coerce the object into the class you need. So if you were to do something like this:
class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } end end
Then you’d have exactly what’s described above, a clean way to use coercion to your advantage. On the other hand, if you’re feeling a little perverse, and want to abuse your newfound knowledge, you can even define it for strings:
class String def to_proc eval "proc { |obj, *args| obj.send(#{self}, *args) }" end end [1, 2, 3].send(&':+, 4') # => [5, 6, 7]
See Also:
- http://www.rubyinside.com/19-rails-tricks-most-rails-coders-dont-know-131.html
- http://blogs.pragprog.com/cgi-bin/pragdave.cgi/Tech/Ruby/ToProc.rdoc
- http://extensions.rubyforge.org/rdoc/index.html
<< Previous: "You can't spell 'function pointers' without 'fun'"
Next: "Making Music with Computers: Two Unconventional Approaches" >>