What exactly does (&:id) do in Product.all.map(&:id) [duplicate]

人盡茶涼 提交于 2019-12-11 19:27:30

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/18523675/what-exactly-does-id-do-in-product-all-mapid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!