Aman King

BlockinatorControl PanelChange LogBrowse PagesSearch?

Blockinator

I have read this blog entry by Jay quite a few times, each time saying to myself, "Yep, understood that." And yes, I do understand... but then later on I find myself unable to recall exactly what I understood.

Hence, as I read that entry yet again, I'm attempting to jot down exactly what I'm understanding... Razz

In Rails, you'll find code like this every once in a while:

area_codes = phone_numbers.collect &:area_code

What's happening here?

  1. Notice that :area_code is being sent as a block to the collect method (a block can be passed to any method as the last argument). The conversion from symbol to block is done by prefixing & to the symbol.
  2. In Ruby, whenever & is prefixed to something and passed as the last argument to a method, that something's to_proc method is invoked.
  3. collect sends, one by one, each element in the array as argument to the passed block, which in this case, is the one returned by the symbol's to_proc.
  4. Normally, Symbol doesn't have to_proc defined but in Rails, Symbol is reopened to define the following:

class Symbol
  def to_proc
    Proc.new { |*args| args.shift.__send__(self, *args) }
  end
end

Note that in the above code, args.shift represents an element of the array, sent by collect.

The rest should make sense on its own now. Smile Hopefully this writing exercise will help my memory serve better.

Tags: technology:ruby, technology:rails, technology:coding Last modified 07:43 Sun, 11 Mar 2007 by AmanKing. Accessed 864 times Children What Links Here share Share Except where expressly noted, this work is licensed under a Creative Commons License.