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 }
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论