Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top