From: Robert Klemme Date: 2010-12-01T18:22:55+09:00 Subject: Re: Object#each ? On Wed, Dec 1, 2010 at 12:00 AM, Andrew Wagner wrote: > On Tue, Nov 30, 2010 at 4:40 PM, Robert Klemme > wrote: > >> On 11/30/2010 06:45 PM, Andrew Wagner wrote: >> >>> On Tue, Nov 30, 2010 at 12:44 PM, Andrew Wagner>> >wrote: >>> >>>  A weird idea just popped into my head: >>>> >>>> class Object >>>>   def each >>>>     yield self >>>>   end >>>> end >>>> >>>> Lets you enumerate without having to worry about whether or not you have >>>> a >>>> collection. Thoughts? Hidden ramifications? >>> >> First of all if you implement #each then you should also include Enumerable >> because the expectation would be that you also have all the nice methods >> like #select, #map etc.  This makes all objects Enumerable which does not >> seem a good idea. > > An interesting point. I think I agree that cluttering Object with all the > Enumerable methods seems like a bad idea. I guess my thinking was that this > would be useful just for the purposes of having #each available, without > including Enumerable. This avoids the [*items] garbage. I usually opt for making things explicit - at least if they are so clutterless as "[*items]". :-) >> One drawback of this approach is that you won't notice if you accidentally >> pass something to a method which should be Enumerable (I mean a real >> collection) - or at least the issue might take some time to be detected. > >  This is an interesting argument, because it sounds an awful lot like the > arguments I usually hear against duck-typing and dynamic typing in general. > Don't those also allow issues which "might take some time to be detected" > too? It seems like the answer is, as always, that's what specs/tests are > for. Hm, not sure I agree. With duck typing you will immediately know if an object does not implement a required method. Granted, you can pass in all objects that satisfy the used contract without "noticing". But then again that's the whole point of duck typing. :-) Maybe my argument is not too important though. The main point would be anyway the first argument against, that then everything is Enumerable and the module Enumerable basically becomes meaningless. > One other thing that I thought of after my original email is that it might > be preferable to change it to "yield self unless nil?", because it could be > odd to have NilClass#each. No. You would simply use inheritance and implement a special version in class NilClass which throws, e.g. class NilClass def each raise NoMethodError, "undefined method `each` for %p" % self end end > Thanks for the thoughts! You're welcome! It's an interesting exchange. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/