From: Robert Klemme Date: 2010-10-07T18:09:13+09:00 Subject: Re: "map" a deeply nested structure: Object#deep_map On Thu, Oct 7, 2010 at 10:22 AM, Guido De Rosa wrote: > Robert Klemme wrote: > >> But according to that logic *all* collections returned should be >> Arrays.  So out = {} would become out = []. > > Enumerable#map returns an Array on any object except wen the object is a > Hash: in such case it returns another Hash. And so should do #deep_map. 11:04:25 ~$ allruby -e 'p({1=>2}.map {|a,b| [b,a]}.class)' CYGWIN_NT-5.1 padrklemme2 1.7.7(0.230/5/3) 2010-08-31 09:58 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] Array ======================================== ruby 1.9.1p429 (2010-07-02 revision 28523) [i386-cygwin] Array ======================================== jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2009-11-02 69fbfa3) (Java HotSpot(TM) Client VM 1.6.0_21) [x86-java] Array I see you noticed already. >> The difference is that in a Hash or Array values are usually uniform >> while with a recursive structure it is much more likely that they are >> not.  So in the case of Enumerable#map you typically know what objects >> you map while in the recursive case you rather need checks. >> >> I still wonder about the usability of this. > > Of course it depends by the usage scenario, and I actually found such a > need in one of my production projects. I may tell you longer detail if > you wish... Yes, please. > Of course there's no need that the values belong to the same class or to > derived class, they just need to be uniform in the duck-typing sense. > > Consider something like: > >    my_deep_structure.deep_map{|v| v.to_s} What do you need that for? If it is for printing or logging then you can use my_deep_structure.to_s or my_deep_structure.inspect. > any of this value may belong to a *different* class but still in > Your::Application::NameSpace:: > > This doesn't appear so uncommon or unrealistic. > > You may have designed your application so that any of your classes > respond to to_s or some other method which "exports" data. > > The result of deep_map will not contain any reference to your > application logic and may easily "inter-operate" with others: I fond > this more convenient that overwriting to_json, to_yaml, marshal_dump and > so on... You really make me curious about your use case. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/