更有效的Ruby方法将对象数组中的属性映射到另一个数组?

时间:2022-08-14 04:18:45

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

1 个解决方案

#1


45  

Use the map method:

使用地图的方法:

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

为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:

[更新]正如Staelen在评论中指出的,这个例子可以进一步缩短为:

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

对于好奇的人来说,这是因为调用to_proc(在一个方法调用中使用)和符号实现to_proc来返回一个Proc,它执行在每个值上的符号所显示的方法(见文档)。

#1


45  

Use the map method:

使用地图的方法:

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

为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:

[更新]正如Staelen在评论中指出的,这个例子可以进一步缩短为:

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

对于好奇的人来说,这是因为调用to_proc(在一个方法调用中使用)和符号实现to_proc来返回一个Proc,它执行在每个值上的符号所显示的方法(见文档)。