From: Guido De Rosa Date: 2010-10-07T17:22:38+09:00 Subject: Re: "map" a deeply nested structure: Object#deep_map Robert Klemme wrote: > OTOH you say you want to mimic #map behavior and since this is part of > the standard behavior people might expect to be able to map keys as > well if this goes into a library. Right. >> >> � �object.deep_map{|x| ... } >> >> by checking block.arity in the implementation code. > > I think that's not necessary. You can just pass an Array to get the > same behavior as Hash#each: > > irb(main):002:0> def f1; yield [1,2] end > => nil > irb(main):003:0> f1 {|a| p a} > [1, 2] > => [1, 2] > irb(main):004:0> f1 {|a,b| p a} > 1 > => 1 > irb(main):005:0> {1=>2}.each {|a,b| p a} > 1 > => {1=>2} > irb(main):006:0> {1=>2}.each {|a| p a} > [1, 2] > => {1=>2} > irb(main):007:0> Ok. Thanks. > 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. > 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... 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} 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... G. -- Posted via http://www.ruby-forum.com/.