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

后端 未结 1 577
日久生厌
日久生厌 2021-02-12 15:14

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
      nam         


        
相关标签:
1条回答
  • 2021-02-12 15:28

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

    0 讨论(0)
提交回复
热议问题