From: Robert Klemme Date: 2009-02-06T23:35:23+09:00 Subject: Re: Array#to_h 2009/2/6 Trans : > On Jan 31, 2:49 pm, Roger Pack wrote: >> Not that I would find it useful at all, but is there is a Hash#to_a >> should there not be an Array#to_h? > > The variety of possible good definitions make this hard to define. So > it's understandable that is is not in Ruby core, though being able to > convert back and forth between Hash#to_a and Array#to_h makes the most > sense. > > I was thinking about it some more and I was thinking about how the > various options might be addressed. So I came up with this: > > # Converts an associative array into a hash. > By using a +mode+ we can offer a variety of common means of > conversion. > > Of course, we could just make them all separate methods, ie. #to_h, > #to_h_array, #to_h_splat, #to_h_flat. Maybe that is better? 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. 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 case when pairs == size to_h_pairs when arr > 0 to_h_multi else to_h_flat end end def to_h_pairs inject({}) {|ha,(k,v)| ha[k]=v; ha} end def to_h_multi inject({}) {|ha,ar| ha[ar.first] = ar[1..-1]; ha} end def to_h_flat each_slice(2).inject({}) {|ha,(k,v)| ha[k]=v; ha} end end [ [1,2,3,4,5], [[1,2],[3,4],[5,6]], [[1,2],[3,4],[5]], [[1,2,3],[4],[5,6]], ].each do |x| p x, x.to_h, "---" end Kind regards robert -- remember.guy do |as, often| as.you_can - without end