From: Nathan Broadbent Date: 2012-11-01T12:08:18+09:00 Subject: [ruby-core:48692] Re: [ruby-trunk - Feature #7241][Open] Enumerable#to_h proposal --14dae9399429a03cdc04cd665460 Content-Type: text/plain; charset=ISO-8859-1 > > Almost no one uses #each_with_object as it is. #each_with_hash is hardly > better. We need a short method name. Moreover I don't think this method's > behavior is really the best approach to the real use case. > It's true that each_with_object doesn't seem to be used too much, but when it is used, the object is usually a hash (for 90% of the cases in Rails, at least.) I think that each_with_hash should be provided for when you want to map an enumerable onto a Hash, but I think that there should also be a 'to_h' method on Array for when you just want to *convert* an Array into a hash. I think 'to_h' would be most useful if it supported the behaviour of both `Hash[ arr ]`, and 'Hash[ *arr ]'. I'm on my phone at the moment, but here's how I could see that working: def to_h if self.all? {|el| el.respond_to? :each && el.size == 2 } Hash[self] else Hash[*self] end end We could just let Hash[] handle any invalid input. --14dae9399429a03cdc04cd665460 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
Almost no one uses #each_with_object as it i= s. #each_with_hash is hardly better. We need a short method name. Moreover = I don't think this method's behavior is really the best approach to= the real use case.

It's true that each_with_object doesn&= #39;t seem to be used too much, but when it is used, the object is usually = a hash (for 90% of the cases in Rails, at least.)

I think that each_with_hash should be provided for when you want to ma= p an enumerable onto a Hash, but I think that there should also be a 't= o_h' method on Array for when you just want to *convert* an Array into = a hash.=A0

I think &= #39;to_h' would be most useful if it supported the behaviour of both `H= ash[ arr ]`, and 'Hash[ *arr ]'.=A0I'm on my phone at the moment, but here's how I could= see that working:

def to_h
=A0 if self.all? {|el| el.respond_to? :ea= ch && el.size =3D=3D 2 }
=A0 =A0 Hash[self]
=A0= else
=A0 =A0 Hash[*self]
=A0 end
end

We could just let Hash[] handle any invalid input.
--14dae9399429a03cdc04cd665460--