Forum: Ruby Enumerable#collect and #select best practices

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-16 20: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:

   enum.select 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
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-16 20:23
(Received via mailing list)
Daniel Schierbeck 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...


Daniel
This topic is locked and can not be replied to.