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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With