Hi –
On Fri, 22 Dec 2006, Jason F. wrote:
On Dec 22, 2006, at 5:27 PM, Christos Z. wrote:
Even shorter:
names = folks.collect(&:name)
I love it! My fantasy has come true. Anyone got a handle on what the & does?
I knew about collect but it alters the original array, which I want to avoid
(shuold’ve said that in my first email, sorry).
collect (aka map) doesn’t alter the original array, unless you use the
! version (collect! or map!). I think one of the people who replied
did use that, but Christos’s version doesn’t.
The & introduces a lambda (an anonymous function, technically an
instance of Proc), to be used as the code block to go with the method
call. For example, look at this:
array = [1,2,3,4,5]
array.map {|e| e * 10 } # [10,20,30,40,50]
and now with a separate lambda:
lam = lambda {|e| e * 10 }
array.map &lam # [10,20,30,40,50]
The reason it works with &:name is that Rails has a to_proc conversion
method for symbols. That method gets called automatically when the &
is applied. When you do &:name, you get a lambda that, if you wrote
it out by hand, would look like this:
lambda {|e| e.send(:name) }
So – the net effect of all of this is that this:
folks.collect(&:name)
calls collect on folks, with a code block (a lambda) that performs the
function of calling the “name” method on each element in folks. The
result is a second, result array, consisting of all the names.
David
–
Q. What’s a good holiday present for the serious Rails developer?
A. RUBY FOR RAILS by David A. Black (Ruby for Rails)
aka The Ruby book for Rails developers!
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)