Ruby trying to grasp a new notation. (inject(: ) vs select(&:even?); why one has &?)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 14:39:19

& operator in this case converts a symbol to a proc. So the code does this under the hood:

[1,2,3,4,5].select {|elem| elem.send :even? } # => [2, 4]

Implementation of inject method recognizes the need for these shortcut method specification and adds a special handling for when symbol is passes as a parameter. So, in this case, it basically does what & operator does.

why one (select) uses the & and the other one (inject) doesn't

Because nobody implemented select this way. Ruby is open-source, they may even accept your patch. Go and fix this :)

P.S.: But if it were up to me, I would instead remove inject's special handling. It feels a little bit redundant and confusing in presence of Symbol#to_proc (that's what & operator uses).

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