Forum: Ruby Enumerable#collect and #select best practices

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Daniel S. (Guest)
on 2006-05-16 22:19
(Received via mailing list)
I need to collect the results of calling a method on each object in an
Enumerable that defines that method. Currently, I have this:

   enum.collect{|obj| obj.a_method rescue nil }.compact

though this could also work: do |obj|
     obj.respond_to? :a_method
   end.collect{|obj| obj.a_method }

although that's a bit verbose.

Is there any best practices I should follow?

Daniel S. (Guest)
on 2006-05-16 22:23
(Received via mailing list)
Daniel S. wrote:
>   enum.collect{|obj| obj.a_method rescue nil }.compact


The simple version didn't work (only in my head), so I'm back at the
verbose version...

This topic is locked and can not be replied to.