RoR
RoR

Reputation: 16502

Ruby on Rails 3 Programming Question

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

Upvotes: 2

Views: 145

Answers (1)

Steve Weet
Steve Weet

Reputation: 28412

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 }

Upvotes: 1

Related Questions