开发者

Ruby on Rails 3 Programming Question

开发者 https://www.devze.com 2023-01-16 22:45 出处:网络
Correct: @teammates = Roster.all.sort_by(&:level) Fails: @teammates = Roster.all.sort_by(:level) What does the & infront of the :leve开发者_JS百科l do? Does it act like a reference like

Correct:

@teammates = Roster.all.sort_by(&:level)

Fails:

@teammates = Roster.all.sort_by(:level)

What does the & infront of the :leve开发者_JS百科l do? Does it act like a reference like in C++?

Thanks in advance


The &symbol notation is some syntactic sugar added by Rails. It is known as symbol to_proc and can be used against any method that expects to receive a Proc.

Array.sort_by expects a proc and this is why just passing the symbol fails. The symbol to_proc syntax arranges for the receiver, in this case sort_by to receive a proc containing the name of a method to call within the proc.

@teammates = Roster.all.sort_by(&:level)

Is equivalent to

@teammates = Roster.all.sort_by{ |obj| obj.level }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号