Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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
like image 265
keruilin Avatar asked Mar 07 '11 05:03

keruilin


1 Answers

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).

like image 200
Michelle Tilley Avatar answered Oct 11 '22 13:10

Michelle Tilley