1

I saw it in some sample Ruby code someone had posted. It was something like:

a.sort_by(&:name)

where a is an array or ActiveRecord objects and :name is one of the attributes.

I have never seen &:name and Ruby's Symbol class documentation says nothing about it. Probably something really simple. :)

Kokizzu
  • 24,974
  • 37
  • 137
  • 233
Colin Wu
  • 611
  • 7
  • 25

1 Answers1

4

Unary Ampersand is address of a function/block/lambda

In this case, it means that the .sort_by function will use each a's element's function named name for comparison

Mostly it used for something else, like this:

[1,2,3].map{ |x| x.to_s } # ['1','2','3']

That could be shortened as:

[1,2,3].map(&:to_s)

So, in your case, a.sort_by(&:name) is a shorthand to:

a.sort_by{ |x| x.name }
Travis
  • 13,311
  • 4
  • 26
  • 40
Kokizzu
  • 24,974
  • 37
  • 137
  • 233