Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does map(&:name) do in this Ruby code?

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.

like image 920
randombits Avatar asked Mar 05 '10 16:03

randombits


People also ask

What does the acronym map stand for?

MAP stands for “minimum advertised price,” and a MAP policy is a legal document brands use to define the lowest possible price a product can legally be advertised for.

What does map stand for on twitter?

The term MAP/NOMAP stands for “minor attracted person” or “non-offensive minor attracted person” is used in their social media profiles to find each other online. Many people who identify as MAP's are using the website Twitter as a support network.

What is map () in Javascript?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements.

What is map with example?

map, graphic representation, drawn to scale and usually on a flat surface, of features—for example, geographical, geological, or geopolitical—of an area of the Earth or of any other celestial body. Globes are maps represented on the surface of a sphere. Cartography is the art and science of making maps and charts.


1 Answers

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' :).

like image 94
Peter Avatar answered Nov 15 '22 22:11

Peter