1

Can any one explain the use of '&' in this piece of ruby code?

s.feature_addons.select(&:is_active?)
Brandon Buck
  • 7,177
  • 2
  • 30
  • 51
jithendhir92
  • 145
  • 1
  • 6

3 Answers3

5

It means:

s.feature_addons.select { |addon| addon.is_active? }

The & calls to_proc on the object, and passes it as a block to the method.

class Symbol
  def to_proc
    Proc.new { |*args| args.shift.__send__(self, *args) }
  end
end

U can define to_proc method in other classes: Examples

Community
  • 1
  • 1
Oleg Haidul
  • 3,682
  • 1
  • 22
  • 14
3

That's a shortcut for to_proc. For example, the code you provided is the equivalent of:

s.feature_addons.select {|addon| addon.is_active?}

Some old documentation for it can be found here:

http://apidock.com/rails/Symbol/to_proc (when it was provided by ActiveSupport)

It then became a part of Ruby core in 1.9

http://www.ruby-doc.org/core-1.9.3/Symbol.html

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
1

You can use this syntax as shorthand for methods to apply to an entire collection.

It is functionally the same as:

s.feature_addons.select { |a| a.is_active? }

You can use it with any collections, such as:

User.all.map(&:id)

etc

Tyler
  • 11,272
  • 9
  • 65
  • 105