10

Trying to understand Ruby a bit better, I ran into this code surfing the Internet:

require 'rubygems'
require 'activeresource'



ActiveResource::Base.logger = Logger.new("#{File.dirname(__FILE__)}/events.log")

class Event < ActiveResource::Base
  self.site = "http://localhost:3000"
end

events = Event.find(:all)
puts events.map(&:name)

e = Event.find(1)
e.price = 20.00
e.save

e = Event.create(:name      => "Shortest event evar!", 
                 :starts_at => 1.second.ago,
                 :capacity  => 25,
                 :price     => 10.00)
e.destroy

What I'm particularly interested in is how does events.map(&:name) work? I see that events is an array, and thus it's invoking its map method. Now my question is, where is the block that's being passed to map created? What is the symbol :name in this context? I'm trying to understand how it works.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
randombits
  • 47,058
  • 76
  • 251
  • 433
  • 2
    This is an exact duplicate of *seven* different questions. And believe me, Ruby hasn't changed that much within the last 3 weeks, so the answers are probably going to be the same: http://StackOverflow.Com/questions/99318/, http://StackOverflow.Com/questions/1217088/, http://StackOverflow.Com/questions/1792683/, http://StackOverflow.Com/questions/1961030/, http://StackOverflow.Com/questions/2096975/, http://StackOverflow.Com/questions/2211751/, http://StackOverflow.Com/questions/2259775/. – Jörg W Mittag Mar 06 '10 at 21:26

1 Answers1

21
events.map(&:name)

is exactly equivalent to

events.map{|x| x.name}

it is just convenient syntactic sugar.

For more details, check out the Symbol#to_proc method here. Here, :name is being coerced to a proc.

By the way, this comes up often here - it's just very hard to google or otherwise search for 'the colon thing with an ampersand' :).

Peter
  • 127,331
  • 53
  • 180
  • 211
  • 3
    Maybe, now that you've mentioned "the colon thing with an ampersand", it will start getting picked up :) – theIV Mar 05 '10 at 17:32