From: Trans Date: 2009-02-07T02:24:31+09:00 Subject: Re: Array#to_h On Feb 6, 9:35 am, Robert Klemme wrote: > This is generally considered better practice over switching behavior > of a method with an argument.  Just think about the length of the > method which increases in with the number of different algorithms > (modes).  I prefer short methods. > > Alternatively make the algorithm detection automatic. Even in that > case I had to_h only do the detection and then delegate to any one of > a number of to_h_ methods.  The rule I follow is to create > methods and classes to do _one_ thing good. > > > But then > > that seems a bit more limiting, less dynamic, less open for new modes > > or multiple labels for a single mode, and the method names look funny > > Not at all: you can simply add another method. True, but adding a new method is a "bigger deal" than just adding another parameter option. But I like your idea, I could create the different methods and then dispatch from to_h, offering the best of both options. > This is how I'd approach it: > > module Enumerable >   def to_h >     pairs = arr = 0 > >     each do |e| >       if Array === e >         if e.size <= 2 >           pairs += 1 >         else >           arr += 1 >         end >       end >     end I'm not sure. On one hand I like it, though I am hesitant about it b/c it means a whole pass over the array upfront, it won't be very fast. What do you think about the performance characteristics? On the other hand, it means the one method #to_h will do quite different things depending on the form of the data structure passed to it. Is that a good idea? T.