map(collect) method on an array of ActiveRecord object

Let's assume there is a model `Member` and the table `members` has a column `name`.

class Member < ActiveRecord::Base
end

You can use map (or collect) method as shown below.

members = Member.find(:all)
member_names = members.map(&:name)

This is thanks to the definition of Symbol#to_proc in ActiveSupport as shown below.

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

The code that uses map method above is equal to the code below.

members = Member.find(:all)
member_names = members.map { |member| member.name }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.