HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyCritical

What does map(&:name) mean in Ruby?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
namerubydoesmeanwhatmap

Problem

I found this code in a RailsCast:

def tag_names
  @tag_names || tags.map(&:name).join(' ')
end


What does the (&:name) in map(&:name) mean?

Solution

It's shorthand for tags.map(&:name.to_proc).join(' ')

If foo is an object with a to_proc method, then you can pass it to a method as &foo, which will call foo.to_proc and use that as the method's block.

The Symbol#to_proc method was originally added by ActiveSupport but has been integrated into Ruby 1.8.7. This is its implementation:

class Symbol
  def to_proc
    Proc.new do |obj, *args|
      obj.send self, *args
    end
  end
end

Code Snippets

class Symbol
  def to_proc
    Proc.new do |obj, *args|
      obj.send self, *args
    end
  end
end

Context

Stack Overflow Q#1217088, score: 551

Revisions (0)

No revisions yet.