0

Here's the line of code I'm trying to wrap my head around:

Category.all.map(&:id).each { |id| Category.reset_counters(id, :products) }

Hoping someone can help me understand what (&:id) is doing and how it impacts the rest of the line? I believe it turns the symbol :id into a proc that'll respond to id?!? But then it gets confusing...

Thanks in advance!

Meltemi
  • 37,979
  • 50
  • 195
  • 293
  • definitely a dupe. though hard to search for that... should have spelled it out "ampersand colon". (i can't delete; it has answers) – Meltemi Aug 30 '13 at 01:53
  • no worries, i searched for lambda operator shortcut rails – jvnill Aug 30 '13 at 01:54
  • 2
    I much prefer this alternative: `Category.all.each { |cat| Category.reset_counters(cat.id, :products) }` – Damien Roche Aug 30 '13 at 01:56
  • that's much easier, for me, to read! – Meltemi Aug 30 '13 at 02:09
  • @jvnill Why would you mark something as a duplicate of something that is itself a duplicate? – Andrew Marshall Aug 30 '13 at 03:16
  • my bad. the first relevant SO result from google using "lambda operator shortcut rails" was that article. I didn't go through the page itself. just copied the url from the google result. i will have to be more careful next time. – jvnill Sep 01 '13 at 02:46

1 Answers1

3
Category.all.map(&:id)

is shorthand for

Category.all.map { |a| a.id }

as for how it affects the rest of the line, the above section returns all id values as a single Array. This Array of ids is then passed into another call to each, which iteratively passes each id into reset_counters.

deefour
  • 34,974
  • 7
  • 97
  • 90