keruilin
keruilin

Reputation: 17512

More efficient Ruby way to map attribute in array of objects to another array?

I won't repeat my question here, but is there are more efficient way to write this?

  def recruits_names
    names = []
    for r in self.referrals do
      names << r.display_name
    end

    return names
  end

Upvotes: 21

Views: 37218

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159105

Use the map method:

Returns a new array with the results of running block once for every element in enum.

def recruits_names
  self.referrals.map { |r| r.display_name }
end

[Update] As indicated by Staelen in the comments, this example can be shortened even further to:

def recruits_names
  self.referrals.map(&:display_name)
end

For the curious, this is because & calls to_proc on the object following it (when used in a method call), and Symbol implements to_proc to return a Proc that executes the method indicated by the symbol on each value yielded to the block (see the documentation).

Upvotes: 61

Related Questions