views:

11

answers:

1

Correct:

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

Fails:

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

What does the & infront of the :level do? Does it act like a reference like in C++?

Thanks in advance

+1  A: 

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 }
Steve Weet