1. Computing

The Magic of Symbol#to_proc

By

How do you convert a Symbol to a Proc? What does it even mean to do that? The Symbol#to_proc method is a shortcut or convenience method used in a variety of places in methods that accept blocks.

How the Explicit Block Parameter Works

But before we jump into using this, let's look at how the & (ampersand) syntax element works. I call this a "syntax element" because it's not technically an operator in this case, I'm referring to the symbol that marks a method parameter or argument as a block.

When you pass an object as an explicit block parameter, Ruby first checks to see if that parameter is a Proc object. If it's not, it will attempt to call its to_proc method. This method should return a Proc object.

To experiment a bit with this, look at the following code. The Debugger object simply prints the name of any unknown method that's called on it, we can use it to demonstrate that the to_proc method is indeed called. The code doesn't do anything interesting though, it just shows how the explicit block parameter works and how it calls to_proc.


#!/usr/bin/env ruby

class Debugger
  def method_missing(meth)
    puts "Method called: #{meth.to_s}"
  end
end

def accepts_block(&block)
  block.call
end

accepts_block( &Debugger.new )

What Symbol#to_proc Does

We're back to the question of what converting a Symbol to a Proc really means. It means nothing, it makes no sense to do this. However, it is used as a shortcut in a very common idiom:


%w{ alice bob carol dave }.map{|name| name.capitalize }

For each name in the list, capitalize it. Now, take a look at this.


%w{ alice bob carol dave }.map(&:capitalize)

This is much cleaner looking. It's much shorter, and has less symbols, and it's pretty clear what the intent is. What Symbol#to_proc does is, when called and passed a single argument, essentially does object.send(self). In other words, if the symbol was :capitalize, then it will call object.send(:capitalize) or object.capitalize.

Where Is This Available?

This feature is available on both 1.8.7 and 1.9.2. It kind of started out as a clever hack, and wasn't available everywhere, but at this point in time, it's safe to use in any code you write.

  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. The Magic of Symbol#to_proc

©2014 About.com. All rights reserved.