O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#40 Elegant Maps and Injects (symbol.rb)

I’ll close this chapter with a tiny script that I didn’t even write. I certainly wish I had, because it’s remarkably useful, especially for making your use of map, inject, and similar methods much more elegant. It’s an example of the best kind of syntactic sugar, and it comes directly from the Ruby Extensions Project at http://extensions.rubyforge.org. This script and all other scripts at that site are licensed under the same terms as Ruby itself, which is what allows me to use it in this chapter.[31] The code is extremely simple.

The Code

#!/usr/bin/env ruby    Symbol.to_proc
class Symbol
  def to_proc()
    Proc.new { |obj, *args| obj.send(self, *args) }
  end
end

What’s the point of this? It lets you use uc_words ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required